#!/bin/sh

curl -X DELETE http://localhost:5984/places
curl -X PUT http://localhost:5984/places
curl -X PUT -d '{"spatial":{"points":"function(doc) {\n    if (doc.loc){\n        emit({\n            type: \"Point\",\ncoordinates: [doc.loc[0], doc.loc[1]]\n        }, [doc._id,doc.loc]);\n    }};"}}' http://localhost:5984/places/_design/main
curl -X PUT -d '{"loc": [-122.270833, 37.804444]}' http://localhost:5984/places/oakland
curl -X PUT -d '{"loc": [10.898333, 48.371667]}' http://localhost:5984/places/augsburg
echo "\n### This request should return 2 rows of data ###"
curl -X GET 'http://localhost:5984/places/_design/main/_spatial/points?bbox=-130,-90,180,90'

LINE_CNT=`curl -s -X GET 'http://localhost:5984/places/_design/main/_spatial/points?bbox=-130,-90,180,90'|wc -l`
if test $LINE_CNT != "4"
then
    echo "(1) test failed"
else
    echo "(1) test ok"
fi


# If you don't restart, everything is fine
# Wait that everything got commit before the restart
sleep 2
curl -X POST -H 'Content-type: application/json' http://localhost:5984/_restart
# Wait for the restart
sleep 3

curl -X PUT -d '{"loc": [17.15, -22.566667]}' http://localhost:5984/places/namibia
echo "\n### This request should return 3 rows of data, not only the one with Namibia ###"
curl -X GET 'http://localhost:5984/places/_design/main/_spatial/points?bbox=-130,-90,180,90'


LINE_CNT=`curl -s -X GET 'http://localhost:5984/places/_design/main/_spatial/points?bbox=-130,-90,180,90'|wc -l`
if test $LINE_CNT != "5"
then
    echo "(2) test failed"
else
    echo "(2) test ok"
fi
