#
# use posgresql DbMirror.pl to mirror a given db
#
#set -x

progname=$(basename $0)

usage()
{
	echo "Usage: $progname host (db1|tm10)"
	exit 1
}

do_tunnel()
{
	# set -x
	# check if tunnel is set up
	# psql -p 2345 -h localhost -l >/dev/null 2>&1
	ps -e -o args | grep "2345:$host:5432" | grep ssh
	if [ "$?" != "0" ]
	then
		# build the tunner
		ssh -L 2345:$host:5432 -N $host >/dev/null 2>&1 &
		sleep 3
	fi
}
	

	

(( $# != 2 )) && usage

host=$1
id=$2

case $id in 
	db1|tm10) ;;
	*)	usage ;;
esac


#
# use $id to construct various variables
#
name=dbmirror_$id
config=$HOME/$id.conf
status_log=$HOME/logs/${name}_status.log
dbmirror_log=$HOME/logs/$name.log
# lock file used by the script to ensure only one program is running 
# at the time.
lock=$HOME/tmp/$name.lock
hostname=$(hostname)

#
# check if it is already running
#
if [ -f "$lock" ]
then
	echo "lock file exists, cannot run $name"
	exit 1
fi

date > $lock

echo "$(date): start $name" >> $status_log

do_tunnel

trap '/bin/rm -f $lock; exit 0' 1 2 3 15
$HOME/dbmirror/DBMirror.pl $config 2>&1 | /usr/sbin/rotatelogs $dbmirror_log 86400
	

echo "$(date): done $name"  >> $status_log

rm -f $lock
exit 0


