#!/bin/sh
set -xe

HOST1=http://localhost:5001
HOST2=http://localhost:5002
LOCAL1=sampledb
LOCAL2=sampledb
DB1="$HOST1/$LOCAL1"
DB2="$HOST2/$LOCAL2"

curl -X DELETE "$DB1"; echo
curl -X DELETE "$DB2"; echo
curl -X PUT "$DB1"; echo
curl -X PUT "$DB2"; echo

resp=`curl -sX PUT -d "{\"hello\":\"world\"}" "${DB1}/doc1"`
echo "$resp"; echo
rev=`expr "$resp" : '.*"rev":"\([^"]*\)"'`

# Replicate
curl -X POST -d "{\"source\":\"$DB1\",\"target\":\"$LOCAL2\"}" "$HOST2/_replicate"; echo
curl -s "$DB1/doc1" | grep world
curl -s "$DB2/doc1" | grep world

# Now make conflicting changes
curl -sX PUT -d "{\"_rev\":\"$rev\",\"hello\":\"fred\"}" "${DB1}/doc1"
curl -sX PUT -d "{\"_rev\":\"$rev\",\"hello\":\"jim\"}" "${DB2}/doc1"
curl -s "$DB1/doc1" | grep fred
curl -s "$DB2/doc1" | grep jim

# Now replicate again
curl -X POST -d "{\"source\":\"$DB1\",\"target\":\"$LOCAL2\"}" "$HOST2/_replicate"; echo
res1=`curl -s "$DB1/doc1"`
res2=`curl -s "$DB2/doc1"`
if [ "$res1" != "$res2" ]; then
  echo "**** OOPS! They should be the same! ****"
  echo -e "$res1\n$res2\n"
fi

# Try the other way round
curl -X POST -d "{\"target\":\"$DB1\",\"source\":\"$LOCAL2\"}" "$HOST2/_replicate"; echo
res1=`curl -s "$DB1/doc1?revs_info=true"`
res2=`curl -s "$DB2/doc1?revs_info=true"`
if [ "$res1" != "$res2" ]; then
  echo "**** OOPS! They should be the same! ****"
  echo -e "$res1\n$res2\n"
fi
echo "**** They should show conflicts?? ****"
