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

# 3/27/03 hctu: we now put table names in a deployment
# since ctu2.1. So let's loaded them
. /home/ctu/crm/bin/crm_tables.sh

crm_all_tables="$crm_tables_pk $crm_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 $crm_all_tables
	do
		psql -c "DROP TRIGGER ${table}_trig ON $table" $dbname
	done
	psql -c "DELETE FROM dbmirror_Pending; DELETE FROM dbmirror_PendingData" $dbname
	exit 0
fi

if [ "$action" = "add" ]
then
	for table in $crm_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 $crm_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 dbmirror_MirrorHost; INSERT INTO dbmirror_MirrorHost (\"slavename\") VALUES('localhost'); " $dbname
fi
	
