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


#
# CRM tables that have Primary Keys: we can add INSERT/DELETE/UPDATE trigger
crm_tables_pk="
	attachment
	b_company
	b_user
	case_detail
	company
	crm_case
	crm_order
	crm_pi
	crm_user
	inquiry
	inventory
	o_item
	oem_product
	order_o_item
	prod_category
	prod_visit
	product
	product_list
	product_list_detail
	product_package
	product_use
	q_item
	quotation
	s_user
	subproduct
	subproduct_cat
	subproduct_cat_value
	"

# CRM tables without Primary Keys: we only add INSERT trigger
crm_tables_no_pk="crm_log"

# 3/27/03 hctu: we now put table names in a deployment
# since ctu2.1. So let's loaded them
. 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 \"Pending\"; DELETE FROM \"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 \"MirrorHost\"; INSERT INTO \"MirrorHost\" (\"HostName\") VALUES('localhost'); " $dbname
fi
	
