#!/bin/bash
# Runs tests for replication including mkrep.sh

/p4/reset_sdp.sh
testfile=test_MultiSDP.py

[[ -L /p4/$testfile ]] || ln -s /sdp/Server/test/$testfile /p4/
[[ -L /p4/test_SDP.py ]] || ln -s /sdp/Server/test/test_SDP.py /p4/

# First setup an instance
python3 test_SDP.py --instance 1 --setup

# Then do mkrep.sh tests
logfile=/tmp/MultiSDPTest.log
python3 /p4/$testfile
result=$?
[[ $result -eq 0 ]] || (tail $logfile && exit $result)

# Finally we use ansible to setup replicas
cd sdp/test
logfile=/tmp/replicas_test.log
ansible-playbook -v -i hosts install_sdp.yaml >> $logfile 2>&1
result=$?
[[ $result -eq 0 ]] || (tail $logfile && exit $result)

# Compare the result to make sure replicas are up-to-date with master
source /p4/common/bin/p4_vars 1
logfile=/tmp/servers.log
p4 servers -J >> $logfile
master=$(cat $logfile | grep -v ' 0/0 ' |grep master | awk '{print $5}')
fs=$(cat $logfile | grep -v ' 0/0 ' |grep _fs_ | awk '{print $5}')
ha=$(cat $logfile | grep -v ' 0/0 ' |grep _ha_ | awk '{print $5}')

[[ "$master" -eq "$fs" && "$master" -eq "$ha" ]] || (cat $logfile && exit 1)

exit $result
