#! /bin/bash

user=$1
pass=$2

cookiejar=$(mktemp)
trap "rm '${cookiejar}'" EXIT

echo "Logging in using $user/$pass"
wget -O /dev/stdout -q --save-cookies "${cookiejar}" "http://localhost:8088/rawman?action=login&username=$user&secret=$pass" || exit $?

dpeers=

while true; do
	echo "SIPPeers"
	npeers=$(wget -O /dev/stdout -q --load-cookies "${cookiejar}" "http://localhost:8088/rawman?action=SIPpeers" | dos2unix | sed -nre 's/^ListItems: //p')
	echo "Found $npeers SIP Peers"

	[ -z "${npeers}" ] && echo "No/failed Response ..." && exit -1
	[ -z "${dpeers}" ] && dpeers=${npeers}
	[ "${npeers}" != "${dpeers}" ] && echo "Number of SIP Peers changed!!" && exit 1

	echo "Issueing reload"
	wget -O /dev/stdout -q --load-cookies "${cookiejar}" "http://localhost:8088/rawman?action=Command&Command=reload" | dos2unix
done
