#!/bin/bash
#
# Database utilities script for the SCMS-SM
#
# description: SCMS Subscriber Management Database Management utility


# ~ expansion for /bin/sh 
pcubehome=`echo ~pcube`
export pcubehome

if . $pcubehome/sm.sh; then
   SQL_DIR=__SQL_DIR__
else
   echo "Failed to load sm.sh - aborting"
   exit 1
fi

# verify UMROOT has a slash at the end
case $UMROOT in
 */) ;;
 *)  UMROOT=$UMROOT/ ;;
esac

# import common functions
if ! . ${UMROOT}bin/clu-common 2>/dev/null; then
    if ! . scripts/clu-common 2>/dev/null; then
        echo "Cannot find clu-common file - exiting"
        exit 1
    fi
fi

exit_if_root()
{
    if [ -w /etc/passwd ]; then 
       echo "This command cannot be run by root" | append_to_tmp_file; 
       write_and_delete_tmp_file_to_clu_log_and_exit 1; 
    fi
}

exit_if_not_root()
{
    if [ -w /etc/passwd ]; then
      echo "running command as root" | append_to_tmp_file 
       #do nothing
    else
       echo "This command can run by root user only" | append_to_tmp_file;
       write_and_delete_tmp_file_to_clu_log_and_exit 1;
    fi
}

HOST_NAME=`hostname`

is_sm_rep1_local()
{
    [ `cat /etc/hosts | grep "$HOST_NAME" | grep SM_REP1 | wc -l` -gt 0 ]
}

is_sm_rep2_local()
{
    [ `cat /etc/hosts | grep "$HOST_NAME" | grep SM_REP2 | wc -l ` -gt 0 ]
}

is_sm_rep1_remote()
{
    [ `cat /etc/hosts | grep "$HOST_NAME" | grep SM_REP1 | wc -l ` -eq 0 ]
}

is_sm_rep2_remote()
{
    [ `cat /etc/hosts | grep "$HOST_NAME" | grep SM_REP2 | wc -l ` -eq 0 ]
}

FILE_NAME="/var/TimesTen/pcubesm22/ttendaemon.options"
is_security_flag_exist()
{
 [ `cat /var/TimesTen/pcubesm22/ttendaemon.options | grep "^\-insecure-backwards-compat" | wc -l ` -eq 1 ]  
}

# create temporary file, along the way redirect all relevant mesages to this file, 
# while the script ends write the file to CLU log in order to improve loging messages.
create_tmp_file
echo "p3db $*" | redirect_to_tmp_file

case "$1" in
  --rep-status)
	exit_if_root

	TT_REP_ADMIN="$(find $PQBHOME/lib/tt -name ttRepAdmin 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_REP_ADMIN" ]; then
            echo "cannot execute $TT_REP_ADMIN" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi

        "$TT_REP_ADMIN" -dsn PCube_SM_Repository -receiver -list 2>&1 | append_to_tmp_file
	
	TT_ISQL="$(find $PQBHOME/lib/tt -name ttIsql 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_ISQL" ]; then
            echo "cannot execute $TT_ISQL" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
        
	if `$TT_ISQL -connStr \"dsn=PCube_SM_Repository\" -f "$SQL_DIR"subrepstatus.sql 2>>$tmp_file_name | grep "TT_REPLICATION_INVALID = 0" &>/dev/null`; then
	    echo "the subscriber DB is ok" | append_to_tmp_file
	else
	    echo "the subscriber DB is in failed state" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
	fi
      ;;

  --rep-stop)
        exit_if_root

	TT_ADMIN="$(find $PQBHOME/lib/tt -name ttAdmin 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_ADMIN" ]; then
            echo "cannot execute $TT_ADMIN"| append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
        "$TT_ADMIN" -repStop PCube_SM_Repository 2>&1 | append_to_tmp_file
      ;;
  
  --destroy-rep-db)
        exit_if_root

	TT_DESTROY="$(find $PQBHOME/lib/tt -name ttDestroy 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_DESTROY" ]; then
            echo "cannot execute $TT_DESTROY" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
        "$TT_DESTROY" "$PQBVAR/tt/PCube_SM_Repository" 2>&1 | append_to_tmp_file
      ;;
      
  --destroy-local-db)
        exit_if_root

	TT_DESTROY="$(find $PQBHOME/lib/tt -name ttDestroy 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_DESTROY" ]; then
            echo "cannot execute $TT_DESTROY" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
        "$TT_DESTROY" "$PQBVAR/tt/PCube_SM_Local_Repository" 2>&1 | append_to_tmp_file
      ;;

  --test-rep-cfg)
        exit_if_root

	if is_sm_rep1_local || is_sm_rep2_remote; then
            echo "Configuration is OK, SM_REP1 is local and SM_REP2 is remote" | append_to_tmp_file
	elif is_sm_rep2_local || is_sm_rep1_remote; then
	    echo "Configuration is OK, SM_REP2 is local and SM_REP1 is remote" | append_to_tmp_file
	elif is_sm_rep1_local || is_sm_rep2_local; then
	    echo "Configuration is WRONG, SM_REP1 and SM_REP2 are configured to be local" | append_to_tmp_file
	    echo "check your /etc/hosts file" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
	else
	    echo "Configuration is WRONG, nor SM_REP1 nor SM_REP2 are configured to be local" | append_to_tmp_file
	    echo "check your /etc/hosts file" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
	fi
	write_and_delete_tmp_file_to_clu_log_and_exit 0
      ;;

  --duplicate)
        exit_if_root

	if is_sm_rep1_local || is_sm_rep2_remote; then
	    LOCAL_HOSTNAME=SM_REP1
	    REMOTE_HOSTNAME=SM_REP2
	elif is_sm_rep2_local || is_sm_rep1_remote; then
	    LOCAL_HOSTNAME=SM_REP2
	    REMOTE_HOSTNAME=SM_REP1
	else
	    echo "Invalid replication alias configuration," | append_to_tmp_file
	    echo "nor SM_REP1 nor SM_REP2 are the local host" | append_to_tmp_file
	    echo "check your configuration in the /etc/hosts file" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
	fi    

	TT_REP_ADMIN="$(find $PQBHOME/lib/tt -name ttRepAdmin 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_REP_ADMIN" ]; then
            echo "cannot execute $TT_REP_ADMIN" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
	"$TT_REP_ADMIN" -dsn PCube_SM_Repository -duplicate -from PCube_SM_Repository -host $REMOTE_HOSTNAME -localhost $LOCAL_HOSTNAME -setMasterRepStart 2>&1 | append_to_tmp_file	
      ;;      

  --duplicate-old)
        exit_if_root

	TT_REP_ADMIN="$(find $PQBHOME/lib/tt -name ttRepAdmin 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_REP_ADMIN" ]; then
            echo "cannot execute $TT_REP_ADMIN" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
	
	if [ `echo "$2" | grep local` ] && [ `echo "$4" | grep remote` ]; then
	    "$TT_REP_ADMIN" -dsn PCube_SM_Repository -duplicate -name PCube_SM_Repository -from PCube_SM_Repository -host $5 -localhost $3 -setMasterRepStart 2>&1 | append_to_tmp_file
	else
            echo "invalid duplicate command" | append_to_tmp_file
	    echo "usage: p3db --duplicate --local LOCAL_HOSTNAME --remote REMOTE_HOSTNAME" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
	fi		
      ;;      
      
  --rep-start)
        exit_if_root

	TT_ADMIN="$(find $PQBHOME/lib/tt -name ttAdmin 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_ADMIN" ]; then
            echo "cannot execute $TT_ADMIN" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
        "$TT_ADMIN" -repStart PCube_SM_Repository 2>&1 | append_to_tmp_file
      ;;

# CSCsq60518 - support cluster upgrade
  --rep-pause)
        exit_if_root

	TT_REP_ADMIN="$(find $PQBHOME/lib/tt -name ttRepAdmin 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_REP_ADMIN" ]; then
            echo "rep-pause: cannot execute $TT_REP_ADMIN" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
	"$TT_REP_ADMIN" -receiver -name PCube_SM_Repository -state pause PCube_SM_Repository 2>&1 | append_to_tmp_file
      ;;
      
  --rep-continue)
        exit_if_root

	TT_REP_ADMIN="$(find $PQBHOME/lib/tt -name ttRepAdmin 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_REP_ADMIN" ]; then
            echo "rep-continue: cannot execute $TT_REP_ADMIN" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
	"$TT_REP_ADMIN" -receiver -name PCube_SM_Repository -state start PCube_SM_Repository 2>&1 | append_to_tmp_file
      ;;

  --sql)
        exit_if_root

	TT_ISQL="$(find $PQBHOME/lib/tt -name ttIsql 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_ISQL" ]; then
            echo "cannot execute $TT_ISQL" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
        "$TT_ISQL" -connStr "dsn=PCube_SM_Repository" -f "$2" 2>&1 | append_to_tmp_file
      ;;

  --sql-local)
        exit_if_root

        TT_ISQL="$(find $PQBHOME/lib/tt -name ttIsql 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_ISQL" ]; then
            echo "cannot execute $TT_ISQL" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
        "$TT_ISQL" -connStr "dsn=PCube_SM_Local_Repository" -f "$2" 2>&1 | append_to_tmp_file
      ;;

  --isql)
        exit_if_root

        TT_ISQL="$(find $PQBHOME/lib/tt -name ttIsql 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_ISQL" ]; then
            echo "cannot execute $TT_ISQL" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
        "$TT_ISQL" -connStr "dsn=PCube_SM_Repository" 2>&1 | append_to_tmp_file
      ;;

  --isql-local)
        exit_if_root

        TT_ISQL="$(find $PQBHOME/lib/tt -name ttIsql 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_ISQL" ]; then
            echo "cannot execute $TT_ISQL" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
        "$TT_ISQL" -connStr "dsn=PCube_SM_Local_Repository" 2>&1 | append_to_tmp_file
      ;;

  --set-rep-scheme)
        exit_if_root

	TT_ISQL="$(find $PQBHOME/lib/tt -name ttIsql 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_ISQL" ]; then
            echo "cannot execute $TT_ISQL" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
        "$TT_ISQL" -connStr "dsn=PCube_SM_Repository" -f "$SQL_DIR"createRep.sql 2>&1 | append_to_tmp_file
      ;;

  --drop-rep-scheme)
        exit_if_root

	TT_ISQL="$(find $PQBHOME/lib/tt -name ttIsql 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_ISQL" ]; then
            echo "cannot execute $TT_ISQL" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
        "$TT_ISQL" -connStr "dsn=PCube_SM_Repository" -f "$SQL_DIR"dropRep.sql 2>&1 | append_to_tmp_file
      ;;

  --update-stats)
        exit_if_root

	TT_ISQL="$(find $PQBHOME/lib/tt -name ttIsql 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_ISQL" ]; then
            echo "cannot execute $TT_ISQL" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
        "$TT_ISQL" -connStr "dsn=PCube_SM_Repository" -f "$SQL_DIR"statsupdate.sql 2>&1 | append_to_tmp_file
      ;;

  --keep-in-mem)
        exit_if_root

  	TT_ADMIN="$(find $PQBHOME/lib/tt -name ttAdmin 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_ADMIN" ]; then
            echo "cannot execute $TT_ADMIN" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
	echo "Subscriber DB" | append_to_tmp_file
        "$TT_ADMIN" -ramPolicy inuse -ramGrace "$2" PCube_SM_Repository 2>&1 | append_to_tmp_file
	echo "Local DB" | append_to_tmp_file
        "$TT_ADMIN" -ramPolicy inuse -ramGrace "$2" PCube_SM_Local_Repository 2>&1 | append_to_tmp_file
      ;;  

  --status)
        exit_if_root

	TT_STATUS="$(find $PQBHOME/lib/tt -name ttStatus 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_STATUS" ]; then
            echo "cannot execute $TT_STATUS" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi
        "$TT_STATUS" 2>&1 | append_to_tmp_file 
      ;;

  --num-of-subs)
        exit_if_root

	TT_ISQL="$(find $PQBHOME/lib/tt -name ttIsql 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_ISQL" ]; then
            echo "cannot execute $TT_ISQL" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi

	subsNum=`"$TT_ISQL" -connStr "dsn=PCube_SM_Repository" -f "$SQL_DIR"subsNum.sql | grep "<" | awk '{print $2}'`
	echo "There are $subsNum subscribers in the DB" | append_to_tmp_file
      ;;      

  --sub-exists)
        exit_if_root

	TT_ISQL="$(find $PQBHOME/lib/tt -name ttIsql 2>>$tmp_file_name | head -1)"
        if [ -d "$TT_ISQL" ]; then
            echo "cannot execute $TT_ISQL" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
        fi

        GET_NAME_SQL="$SQL_DIR/get_name.sql"

	if [[ -a $SQL_DIR/tmp.sql ]]; then		
	    # remove the file only if exist
	    rm $SQL_DIR/tmp.sql
	fi
	
	sed "s;__NAME__;$2;g" $GET_NAME_SQL > $SQL_DIR/tmp.sql
	chmod 755 $SQL_DIR/tmp.sql

	#"$TT_ISQL" -connStr "dsn=PCube_SM_Repository" -f $pcubehome/sm/server/bin/sql/tmp.sql
	#"$TT_ISQL" -connStr "dsn=PCube_SM_Repository" -f $pcubehome/sm/server/bin/sql/tmp.sql | grep "1 rows found"

	if [ `"$TT_ISQL" -connStr "dsn=PCube_SM_Repository" -f $SQL_DIR/tmp.sql | grep "1 row found" | wc -l` -gt 0 ]; then
            echo "$2 exists in the subscriber DB" | append_to_tmp_file
	else
	    echo "$2 does not exist in the subscriber DB" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
	fi
      ;;

  --upgrade-rep-protocol)
        exit_if_not_root
        $PQBHOME/sm/server/bin/p3db --remove-security-flag 2>&1 | append_to_tmp_file
        su - pcube -c "$PQBHOME/sm/server/bin/p3db --rep-stop" 2>&1 | append_to_tmp_file
        su - pcube -c "$PQBHOME/sm/server/bin/p3sm --stop" 2>&1 | append_to_tmp_file
        /etc/init.d/tt_pcubesm22 restart 2>&1 | append_to_tmp_file
        su - pcube -c "$PQBHOME/sm/server/bin/p3sm --start --wait" 2>&1 | append_to_tmp_file
        su - pcube -c "$PQBHOME/sm/server/bin/p3db --rep-start" 2>&1 | append_to_tmp_file
      ;;
  
  --check-security-flag)
        if is_security_flag_exist; then
	    echo "security backward flag exists" | append_to_tmp_file
	else
	    echo "security backward flag does not exist" | append_to_tmp_file
            write_and_delete_tmp_file_to_clu_log_and_exit 1
	fi	    
      ;;

  --add-security-flag)
        if is_security_flag_exist; then
	    echo "security flag exists" | append_to_tmp_file
	else
            echo "adding SM Database security backward flag" | append_to_tmp_file
	    line="-insecure-backwards-compat"
	    cat $FILE_NAME > $FILE_NAME.0
	    echo $line >> $FILE_NAME.0
            cp $FILE_NAME.0 $FILE_NAME
            /etc/init.d/tt_pcubesm22 restart 2>&1 | append_to_tmp_file
	fi	    
      ;;

  --remove-security-flag)
        if is_security_flag_exist; then
	    echo "removing SM Database security backward flag" | append_to_tmp_file
	    line="insecure"
 	    cat $FILE_NAME | grep -v $line > $FILE_NAME.0
	    cp $FILE_NAME.0 $FILE_NAME
	else
	    echo "security flag does not exist" | append_to_tmp_file
	fi	    
      ;;
  *)
	echo "Usage p3db [--rep-status | --rep-start | --rep-stop | 
			--rep-pause | --rep-continue
            --destroy-rep-db | --destroy-local-db | --set-rep-scheme |
            --drop-rep-scheme | --status | --keep-in-mem SECS |
            --duplicate | --upgrade-rep-protocol]
    --rep-status           status of the replication agent
    --rep-start            start the replication agent
    --rep-stop             stop the replication agent
    --rep-pause            pause the replication agent
    --rep-continue         continue the replication agent which is in pause state
    --set-rep-scheme       assign a replication scheme to the database 
    --drop-rep-scheme      drop the replication scheme from the database 
    --status               display the DB status
    --destroy-rep-db       destroy the replicated data-store
    --destroy-local-db     destroy the local data-store
    --duplicate            copy the data-store from the 'remote' machine to
                           the 'local' machine 
    --upgrade-rep-protocol upgrade the replication protocol between DBs in the cluster
    --keep-in-mem SECS     sets a timeout that the database will be kept in the
                           shared-memory from the time the last connection to
						   the DB is down this improves the SM restart time
    --help                 display this message
    --num-of-subs          display current number of subscribers in the database
    --sub-exists           verifies whether certain subscriber exists in the database"
    ;;
	
esac
   
# write and delete temporary file to CLU log 
write_and_delete_tmp_file_to_clu_log
echo "Command terminated successfully"

				      

