#
# This script add/remove DbMirror triggers to TM tables
#	Usage: ... [-r] dbname
#		-r: remove (default is to add)
#

. /home/ctu/tm/bin/tm_tables.sh

tm_all_tables="$tm_tables_pk $tm_tables_no_pk"

progname=$(basename $0)
function usage() {
	echo "Usage: $progname [-r] dbname"
	echo "      -r: remove triggers, default is to add triggers"
}

action="add"
if [ "$1" = "-r" ]
then
	shift
	action="del"
fi

if [ "$#" != "1" ]
then
	usage
	exit 1
fi

set -x
dbname=$1

if [ "$action" = "del" ]
then
	for table in $tm_all_tables
	do
		psql -c "DROP TRIGGER ${table}_trig ON $table" $dbname
	done
	psql -c "DELETE FROM \"Pending\"; DELETE FROM \"PendingData\"" $dbname
	exit 0
fi

if [ "$action" = "add" ]
then
	for table in $tm_tables_pk
	do
		psql -c "CREATE TRIGGER ${table}_trig  AFTER INSERT OR DELETE OR UPDATE ON $table FOR EACH ROW EXECUTE PROCEDURE recordchange (); " $dbname
	done


	for table in $tm_tables_no_pk
	do
		psql -c "CREATE TRIGGER ${table}_trig  AFTER INSERT ON $table FOR EACH ROW EXECUTE PROCEDURE recordchange (); " $dbname
	done

	psql -c "DELETE FROM \"MirrorHost\"; INSERT INTO \"MirrorHost\" (\"HostName\") VALUES('localhost'); " $dbname
fi
	
