#!/bin/bash
set -xe

environment(){
if [ ! -f site-a.conf ] && [ ! -L site-a.conf ]; then
	ln -s run/site-a/ceph.conf site-a.conf
fi

if [ ! -f site-b.conf ] && [ ! -L site-b.conf ]; then
	ln -s run/site-b/ceph.conf site-b.conf
fi

}
stop(){
sudo ip netns exec east ../src/mstop.sh site-a
sudo ip netns exec west ../src/mstop.sh site-b
sudo killall rbd-mirror
sudo killall rbd-mirror
sudo killall rbd-mirror
}
start(){
sudo ip netns exec east bash -c "MON=1 OSD=1 MGR=1 MDS=0 RGW=0 ../src/mstart.sh clustera --short -n -d --without-dashboard" 
sudo ip netns exec west bash -c "MON=1 OSD=1 MGR=1 MDS=0 RGW=0 ../src/mstart.sh clusterb --short -n -d --without-dashboard"

sudo ip netns exec east ./bin/ceph --cluster site-a osd pool create pool1
sudo ip netns exec east ./bin/rbd --cluster site-a pool init pool1
 
sudo ip netns exec west ./bin/ceph --cluster site-b osd pool create pool1
sudo ip netns exec west ./bin/rbd --cluster site-b pool init pool1

#set to image mirror
sudo ip netns exec east ./bin/rbd --cluster site-a mirror pool enable pool1 image

#create token
sudo ip netns exec east ./bin/rbd --cluster site-a mirror pool peer bootstrap create pool1 | tail -n 1 > token

#import token
sudo ip netns exec west ./bin/rbd --cluster site-b mirror pool peer bootstrap import --site-name site-b pool1 token

sudo ip netns exec east ./bin/rbd-mirror --cluster site-a --rbd-mirror-delete-retry-interval=5 --rbd-mirror-image-state-check-interval=5 --rbd-mirror-journal-poll-age=1 --rbd-mirror-pool-replayers-refresh-interval=5 --debug-rbd=40 --debug-journaler=40 --debug-rbd_mirror=40 --daemonize=true
sudo ip netns exec west ./bin/rbd-mirror --cluster site-b --rbd-mirror-delete-retry-interval=5 --rbd-mirror-image-state-check-interval=5 --rbd-mirror-journal-poll-age=1 --rbd-mirror-pool-replayers-refresh-interval=5 --debug-rbd=20 --debug-rbd-mirror=20 --daemonize=true

sudo ip netns exec east ./bin/rbd --cluster site-a create pool1/test-demote-sb --size 100G --image-feature layering --image-feature exclusive-lock --image-feature object-map --image-feature fast-diff --debug-ms 0 --debug-rbd 20 --debug-rbd-mirror 20

sudo ip netns exec east ./bin/rbd --cluster site-a mirror image enable pool1/test-demote-sb snapshoti
sudo ip netns exec east ./bin/rbd --cluster site-a mirror snapshot schedule add --pool pool1 --image test-demote-sb 1m
}

NUM_ARGS=`echo "$@" | awk '{print NF}'`
ACTION=$1
if [ "$ACTION" == "start" ]; then
	echo setting up environment
	environment
	echo start
	start
elif [ "$ACTION" == "stop" ]; then
	echo stop
	stop
else
	echo "Option not recognized"
fi
