# some common definitions for sm install scripts
# this should be included as:   ". sm-common.sh"


this_script="${0##*/}"
platform=`uname`

amiroot () {
   [ -w /etc/passwd ]
}

append_log () {
    (printf "$this_script: "; cat) | tee >(logger -p daemon.notice)
}

echo_log () {
    echo "$*" | append_log
}

err_and_exit () {
    # arg1 - message, arg2 - exit status
    echo_log "Error - $1 - exiting."
    exit $2
}

ensure_disk_space () {
    # make sure there are at least arg1 KBYTES free on
    # the device where the directory arg2 resides


    #If the path contains "VRTS" - do not use -P switch
    #which df
    dfpath="$(which df | grep -c 'VRTS')"
    echo_log $dfpath

    if [ $dfpath -eq 1 ]; then
          [ "$(df -k $2 |tail -1 |awk '{print $4}')" -ge $1  ]
    elif is_linux; then
          [ "$(df -k -P $2 |tail -1 |awk '{print $4}')" -ge $1 ]
    else
       [ "$(df -k $2 |tail -1 |awk '{print $4}')" -ge $1 ]
    fi
}

pcube_user_exists () {
    echo_log "Verifying user and group for P-Cube ..."
    u="$(grep -c '^pcube:' /etc/passwd)"
    g="$(grep -c '^pcube:' /etc/group)"

    [ $u -eq 1 ] && [ $g -eq 1 ]
}

load_sm_sh () {
    . $PQBHOME/sm.sh &&
        echo_log "loaded current sm.sh" || {
            echo_log "failed to download current sm.sh"
            return 1
        }
    # we now have definitions for UMROOT, PQBHOME, PQBVAR
    
    # if PQBJAVA is not defined (versions 2.2 and down, define it to java)
    [ -z $PQBJAVA ] && {
	export PQBJAVA=java
    }
    
    return 0
}    

# This function is used to set properties in sm.sh
# if the key already exist the function replaces its value
# otherwise it adds a new key and value
set_property_in_sm_sh () {
   cp "$PQBHOME"/sm.sh "$PQBHOME"/sm.sh.bak
   cat $PQBHOME/sm.sh | grep -v $key > "$PQBHOME"/sm.sh.bak
   printf '%s=%s\n' "$key" "$val" >> "$PQBHOME"/sm.sh.bak
   mv "$PQBHOME"/sm.sh.bak "$PQBHOME"/sm.sh
}

is_linux () {
    # check if we are running on Linux
    [ $platform == "Linux" ]
}

is_solaris () {
    # check if we are running on Solaris
    [ $platform == "SunOS" ]
}

# Exit if seLinux status is enabled
check_se_linux () {
    seLinux="$(/usr/sbin/sestatus | head -1 | cut -d' ' -f19)"
    echo_log "Checking seLinux status during installation : $seLinux"
   [ $seLinux == "disabled" ]
}

# This function is relevant on linux platforms only
# 'uname -m' sample output for RH4 64 bit: x86_64
# 'uname -m' sample output for RH4 32 bit: i686
is_linux_64bit() {
 [ "$(uname -m | grep -c '64')" -eq 1 ]
}

# This function is relevant on linux platforms only
is_intel_processor() {
   [ "$(grep -c 'Intel' /proc/cpuinfo)" -ge 1 ]
}

# This function is relevant on linux platforms only
is_amd_processor() {
   [ "$(grep -c 'AMD' /proc/cpuinfo)" -ge 1 ]
}

tt_exists () {
	ttadmin="$(find $PQBHOME/lib/tt -name ttAdmin 2>/dev/null | head -1)"
	[ -x "$ttadmin" ] || {
     
     # Exit - TimesTen does not exist 
	  return 1
	}
   return 0
}

ram_policy_without_grace_period () {
	ttadmin="$(find $PQBHOME/lib/tt -name ttAdmin 2>/dev/null | head -1)"
	[ -x "$ttadmin" ] && echo_log "checking RAM policy" || {
	  echo_log "cannot execute ttadmin"

     # Exit - TimesTen does not exist therefore no grace period is configured
	  return 0
	}

	isGrace=$("$ttadmin" -query PCube_SM_Repository | grep RAM | grep -c grace)
	[ $isGrace -eq 0 ] 
}

# check SM mode. possible modes: 32/64
# check current mode, calculate new mode based on old mode and user response
check_sm_mode () {
    ttversion="$(find $PQBHOME/lib/tt -name ttVersion 2>/dev/null | head -1)"
    [ -x "$ttversion" ] && echo_log "checking SM Database version" || {
	echo_log "cannot execute $ttversion"
	return 1
    }
    export TT_VERSION="$($ttversion | head -1 | cut -d' ' -f3)"
    export TT_VERSION_MAJOR="$(echo $TT_VERSION | cut -d'.' -f1)"
    export TT_VERSION_MINOR="$(echo $TT_VERSION | cut -d'.' -f2)"
    
    if [ "$TT_VERSION_MAJOR" = "5" ]; then
       export SM_OLD_MODE="$($ttversion | head -1 | cut -d' ' -f4 | cut -d'(' -f2)"
    elif [ "$TT_VERSION_MAJOR" = "6" ]; then
       export SM_OLD_MODE="$($ttversion | head -1 | cut -d' ' -f4 | cut -d'(' -f2)"
    else
       export SM_OLD_MODE="32"
    fi

    export SM_NEW_MODE="$SM_BIT_OPTION"    
}

load_tt_info() {
    ttversion="$(find $PQBHOME/lib/tt -name ttVersion 2>/dev/null | head -1)"
    [ -x "$ttversion" ] && echo_log "checking SM Database version" || {
	echo_log "cannot execute $ttversion"
	return 1
    }
    export TT_VERSION="$($ttversion | head -1 | cut -d' ' -f3)"
    export TT_VERSION_MAJOR="$(echo $TT_VERSION | cut -d'.' -f1)"
    export TT_VERSION_MINOR="$(echo $TT_VERSION | cut -d'.' -f2)"
    export TT_BIT_OPTION="$($ttversion | head -1 | cut -d' ' -f4 | cut -d'(' -f2)"
    echo_log "SM Database bit option: $TT_BIT_OPTION"
    return 0
}

# ----------------------------------------------------------------------------------
# uninstall functions - used by uninstall-sm.sh and upgrade-sm.sh
# ----------------------------------------------------------------------------------

stop_existing_sm () {
   echo_log "Stopping existing SM "
   # the 3rd pipe makes sure that the line of the grep process won't appear in the output
   [ ! -z "$( ps -ef | grep java.*SMSERVER | grep -v grep )" ] || {
         echo_log "Existing SM is already down"
     return
   }
   su - pcube -c "$PQBHOME/sm/server/bin/p3sm --stop"
}

start_existing_sm () {
   echo_log "Sarting existing SM "
   # the 3rd pipe makes sure that the line of the grep process won't appear in the output
   [ -z "$( ps -ef | grep java.*SMSERVER | grep -v grep )" ] || {
         echo_log "Existing SM is already up"
     return
   }
   su - pcube -c "$PQBHOME/sm/server/bin/p3sm --start"
}

stop_replication_agent () {
    ttadmin="$(find $PQBHOME/lib/tt -name ttAdmin 2>/dev/null | head -1)"
    [ -x "$ttadmin" ] && echo_log "stopping SM Database replication" || {
      echo_log "cannot execute $ttadmin"
      return 1
    }

    "$ttadmin" -repStop PCube_SM_Repository >& /dev/null
    return 0		
}

start_replication_agent () {
    ttadmin="$(find $PQBHOME/lib/tt -name ttAdmin 2>/dev/null | head -1)"
    [ -x "$ttadmin" ] && echo_log "starting SM Database replication" || {
      echo_log "cannot execute $ttadmin"
      return 1
    }

    "$ttadmin" -repStart PCube_SM_Repository >& /dev/null
    return 0		
}

destroy_data_store() {
   ttdestroy="$(find $PQBHOME/lib/tt -name ttDestroy 2>/dev/null | head -1)"
   [ -x "$ttdestroy" ] && echo_log "removing SM Database data store" || {
     echo_log "cannot execute $ttdestroy"
     return 1
   }
      # Restart TimesTen Daemon 
    TT_DAEMON="$(find $PQBHOME/lib/tt -name ttDaemonAdmin 2>/dev/null | head -1)"
    $TT_DAEMON -restart

    #  To findout the PCube_SM_Repository DataStore path in sys.odbc.ini file
    dataStoreStr="DataStore"
    equal="="
    Str_SM_Repository="$(grep -e "^\s*DataStore.*/PCube_SM_Repository" /var/TimesTen/sys.odbc.ini)"
    result=$(echo ${Str_SM_Repository} | sed "s/${dataStoreStr}/\ /g")
    PCube_SM_Repository_DataStore_Path=$(echo ${result} | sed "s/${equal}/\ /g")
   
    #  To findout the PCube_SM_Local_Repository DataStore path in sys.odbc.ini file
    Str_SM_Local_Repository="$(grep -e "^\s*DataStore.*/PCube_SM_Local_Repository" /var/TimesTen/sys.odbc.ini)"
    result=$(echo ${Str_SM_Local_Repository} | sed "s/${dataStoreStr}/\ /g")
    PCube_SM_Local_Repository_DataStore_Path=$(echo ${result} | sed "s/${equal}/\ /g")

   su - pcube -c "$ttdestroy -force $PCube_SM_Repository_DataStore_Path"
   su - pcube -c "$ttdestroy -force $PCube_SM_Local_Repository_DataStore_Path"
}

fix_tt_uninst_bug () {
    # first determine currently installed TimesTen version
    ttversion="$(find $PQBHOME/lib/tt -name ttVersion 2>/dev/null | head -1)"
    [ -x "$ttversion" ] && echo_log "checking SM Database version" || {
	echo_log "cannot execute $ttversion"
	return 1
    }
    export TT_VERSION="$($ttversion | head -1 | cut -d' ' -f3)"
    export TT_VERSION_MAJOR="$(echo $TT_VERSION | cut -d'.' -f1)"
    export TT_VERSION_MINOR="$(echo $TT_VERSION | cut -d'.' -f2)"

    if [ "$TT_VERSION_MAJOR" = "5" ] && [ "$TT_VERSION_MINOR" = "0" ]; then
	echo_log "fixing SM Database uninst.sh due to a bug in version 5.0"
	ttuninst="$(find $PQBHOME/lib/tt -name uninst.sh 2>/dev/null | head -1)"
	[ -x "$ttuninst" ] || {
	    echo_log "cannot find $ttuninst"
	    return 1
	}
	tmp_tt_uninst=/tmp/tt_uninst.sh
	cp "$ttuninst" "$tmp_tt_uninst"
	sed -e "s/grep \"\$2\$4/grep \"\$2/" "$tmp_tt_uninst" > "$ttuninst"
    fi
}

# db_upgrade_mode used as input to this functions
# db_upgrade_mode = leave_as_is - the data store will not be removed during uninstall proces
# otherwise the data store will be removed
uninstall_tt () {
    # At version 5.0 TT file uninst.sh should be modified to enable batch uninstall
    fix_tt_uninst_bug
    
    #CSCuj59556 - Uninstallation is not working due to default pcube (/opt/pcube/) directory in uninstall reponse file 
    # So we are updating current pcube directory in uninstall reponse file when current pcube directory does not match with /opt/pcube/ 
    default_pcube="/opt/pcube/"
    if [ "$default_pcube" != "$PQBHOME/" ]; then
    sed "s;$default_pcube;$PQBHOME/;g" TimesTen/pqb_resp_uninst.txt > TimesTen/uninst_resp_modified.txt
    mv -f TimesTen/uninst_resp_modified.txt TimesTen/pqb_resp_uninst.txt
    fi

    tt_uninst_resp="TimesTen/pqb_resp_uninst.txt"
    tmp_uninst_resp=/tmp/pqb_resp_uninst.txt
    
    # preape uninstall response file according to db-mode flag
    # if (db_upgrade_mode = leave-as-is) data store is not removed
    # if (db_upgrade_mode = destroy or export-import) data store is removed
    if [ "$db_upgrade_mode" = "leave-as-is" ]; then
	sed -e "s/Would you also like to remove all files in \/var\/TimesTen\/pcubesm22:./Would you also like to remove all files in \/var\/TimesTen\/pcubesm22:n/" "$tt_uninst_resp" > "$tmp_uninst_resp"
    else
	sed -e "s/Would you also like to remove all files in \/var\/TimesTen\/pcubesm22:./Would you also like to remove all files in \/var\/TimesTen\/pcubesm22:y/" "$tt_uninst_resp" > "$tmp_uninst_resp"
    fi
    
    #CSCuj59556 - Uninstall response file updated with default pcube (/opt/pcube/) directory when current pcube directory does not match with /opt/pcube/
    if [ "$default_pcube" != "$PQBHOME/" ]; then  
    sed "s;$PQBHOME/;$default_pcube;g" TimesTen/pqb_resp_uninst.txt > TimesTen/uninst_resp_modified.txt
    mv -f TimesTen/uninst_resp_modified.txt TimesTen/pqb_resp_uninst.txt
    fi
    
    # perform uninstall
    ttsetup="$(find $PQBHOME/lib/tt -name setup.sh 2>/dev/null | head -1)"
    [ -x "$ttsetup" ] && echo_log "removing SM Database using script $ttsetup" || {
	echo_log "cannot execute $ttsetup"
	return 1
    }
    "$ttsetup" -uninstall -batch $tmp_uninst_resp
    stat=$?
    [ $stat -eq 0 ] || {
	echo_log "problem with SM Database uninstall - skipping link and var removal"
	return $stat
    }
    
    # remove the lib directory used by TT after uninstallation
    rm -rf $PQBHOME/lib &>/dev/null &&
	echo_log "removed SM Database lib directory $PQBHOME/lib" ||
	echo_log "warning - problem removing SM Database lib directory $PQBHOME/lib"
	
    rm -rf $PQBHOME/classes &>/dev/null &&
	echo_log "removed SM Database symlinks in directory $PQBHOME/classes" ||
	echo_log "warning - problem removing SM Database symlinks in directory $PQBHOME/classes"
	
    #Delete an ttadmin group from the TimesTen instance administrators group
	  groupdel ttadmin 2>/dev/null && 
  echo_log "removed ttadmin group" ||
  echo_log "warning - problem removing ttadmin group"

}

drop_replication_scheme_clu(){
   su - pcube -c "$PQBHOME/sm/server/bin/p3db --drop-rep-scheme"
   echo_log "removed SM Database replication scheme" 
}

drop_replication_scheme(){
TT_ISQL="$(find $PQBHOME/lib/tt -name ttIsql 2>/dev/null | head -1)"
        if [ -d "$TT_ISQL" ]; then
            echo "cannot execute $TT_ISQL"
            exit 1
        fi
#SM Database replication scheme can be removed only by pcube user          
        su pcube -c "$TT_ISQL -connStr dsn=PCube_SM_Repository -f ./scripts/dropRep.sql"
        echo_log "removed SM Database replication scheme" 
}

set_replication_scheme_clu(){
   su - pcube -c "$PQBHOME/sm/server/bin/p3db --set-rep-scheme"
   echo_log "set SM Database replication scheme" 
}

###################################################
# Upgrade functions
###################################################

check_tt_upgrade_mode () {
    if [ "$SM_OLD_VERSION_MAJOR$SM_OLD_VERSION_MINOR$SM_OLD_MODE" = "$SM_NEW_VERSION_MAJOR$SM_NEW_VERSION_MINOR$SM_NEW_MODE" ]; then
       if [[ $sm == "second" ]]; then
          # in cluster setup we want the DB to be duplicated when on a second machine
          export db_upgrade_mode="export-import"          
       else
      	# upgrade between builds with the same bit option
      	export db_upgrade_mode="leave-as-is"
       fi
       export upgrade_tt="false"
    else
	# all other upgrade require a full database installation (unless the user requested to destroy its contents) 
        export upgrade_tt="true"
	     export db_upgrade_mode="export-import"
    fi

    return 0
}


get_new_sm_version () {
    local version="$(cat MANIFEST | grep -i 'SM Version' | awk '{print $3, $4, $5}')"
    [ $? ] || return 1
    echo_log "New SM version is $version"
    # Note: This depends on rigid format of the version string (... Major.Minor...)
    export SM_NEW_VERSION="$version"
    export SM_NEW_VERSION_MAJOR="$(echo $version | cut -d' ' -f1 | cut -d. -f1 )"
    export SM_NEW_VERSION_MINOR="$(echo $version | cut -d' ' -f1 | cut -d. -f2 )"
    local tempMinor="$(echo $version | cut -d' ' -f1 | cut -d. -f3 )"
    export SM_NEW_VERSION_MINOR_MINOR="${tempMinor%[A-Z]}"
    export SM_NEW_VERSION_BUILD=$(echo "${version#*Build}")    
    [ "$version" ]
}

get_sm_version () {
    local version="$(su - pcube -c "$PQBHOME/sm/server/bin/p3sm --version" | grep Build)"
    [ $? ] || return 1
    echo_log "Existing SM version is $version"
    # keep the old version number for later inspection.
    # Note: This depends on rigid format of the version string (... Major.Minor...)
    export SM_OLD_VERSION="$version"
    export SM_OLD_VERSION_MAJOR="$(echo $version | cut -d' ' -f1 | cut -d. -f1 )"
    export SM_OLD_VERSION_MINOR="$(echo $version | cut -d' ' -f1 | cut -d. -f2 )"
    local tempMinor="$(echo $version | cut -d' ' -f1 | cut -d. -f3 )"
    export SM_OLD_VERSION_MINOR_MINOR="${tempMinor%[A-Z]}"
    export SM_OLD_VERSION_BUILD=$(echo "${version#*Build}")   
    [ "$version" ]
}

old_sm_installed () {
    [ -d $PQBHOME/sm ] && get_sm_version
}

sm_is_2_2_and_up () {
   # Note: this should always be called AFTER old_sm_installed (or get_sm_version)
    if [ $SM_OLD_VERSION_MAJOR -eq "2" ] && [ $SM_OLD_VERSION_MINOR -ge "2" ]; then
	return 0
    elif [ $SM_OLD_VERSION_MAJOR -eq "3" ]; then
	return 0
    elif [ $SM_OLD_VERSION_MAJOR -eq "4" ]; then
	return 0
    elif [ $SM_OLD_VERSION_MAJOR -eq "5" ]; then
	return 0
    else
	return 1
    fi
}


remove_tt () {
    if [ "$(type -t remove_tt_hook)" ]; then
        # the user has defined a hook for removing TT, we use
        # it instead of the default action
        echo_log "calling user-defined remove_tt_hook"
        remove_tt_hook
	return 0
    fi

    if [ "$upgrade_tt" = "true" ] || [ "$db_upgrade_mode" = "destroy" ] || [[ "$sm" == "second" ]]; then

	   # first stop replication agent (relevant for cluster environment only)
      stop_replication_agent || return 1

      # drop replication scheme (for cluster, no harm on standalone)
      drop_replication_scheme || return 1
   
	   # then destroy the data store
      if [ "$db_upgrade_mode" != "leave-as-is" ]; then
         destroy_data_store || return 1
      fi

	   # then perform uninstall   
      if [ "$upgrade_tt" = "true" ]; then
         uninstall_tt || return 1
      fi 


    fi
}


start_sm () {
    $tt_etc_init start &&
        echo_log "SM Database started" ||
        echo_log "SM Database not started"   # eg if it was already running
    
    sleep 5 # let TT get its bearings
    
    echo_log "Starting SM"
    su - pcube -c "$PQBHOME/sm/server/bin/p3sm --start --wait"
}

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 ]
}

call_hook () {
    # if the hook whose name is arg1 has been defined, call it.
    
	if [ "$(type -t $1)" ]; then
	        echo_log "calling user-defined hook $1"
	        $1
    else
        echo_log "no hook has been defined for $1"
    fi
}

print_pqi_notice () {
    echo_log "***********************************************************"
    echo_log " Do not forget to perform the following operations: "
    echo_log " 1. Perform the operations described in the 'Upgrade'"
    echo_log "    chapter of the SM User Guide"
    echo_log " 2. Install application PQI or LEG PQIs"
    echo_log "    Use CLU p3inst --install -f <pqi file>  "    
    echo_log "    CLU must be run by user pcube "
    echo_log "***********************************************************"
}

init_SQL_DIR_in_scripts_directory(){
   export current_dir=$(pwd)

   # init __SQL_DIR__ in scripts/p3db
   SQL_DIR=$PQBHOME/sm/server/bin/sql/
   sed "s;__SQL_DIR__;$SQL_DIR;g" $current_dir/scripts/p3db > $current_dir/scripts/p3db1
   mv $current_dir/scripts/p3db1 $current_dir/scripts/p3db
   chmod 755 $current_dir/scripts/p3db
}

get_subscribers_num(){

   export current_dir=$(pwd)

    # get current number of subs
    export currentSubsNum=`su - pcube -c "$current_dir/scripts/p3db --num-of-subs" | grep "subscribers in the DB" | awk '{print $3}'`

    if [ ! "$currentSubsNum" ]; then
       export currentSubsNum=0
    fi

    #if [ "$currentSubsNum"="subscribers" ]; then
    #    export currentSubsNum=0
    #fi
}


call_verify_config() {
    export current_dir=$(pwd)

    # Need this for Java
    if ! . $PQBHOME/sm.sh; then
       echo "Cannot find SM Java definitions - exiting"
       exit 1
    fi

    # call upgrade config function
    local lib="$PQBHOME/sm/server/lib"
    local verifyOnly="true"
    if [ ! "$currentSubsNum" ]; then 
       export currentSubsNum=0
    fi

    echo_log "Current subscribers number: $currentSubsNum"
    out="$($PQBJAVA -cp scripts/log4j.jar:scripts/upgrade.jar:$lib/xerces.jar UpgradeSmAndSysOdbcConfig $PQBHOME/sm/server/root $SM_OLD_VERSION_MAJOR $SM_OLD_VERSION_MINOR $SM_NEW_VERSION_MAJOR $SM_NEW_VERSION_MINOR /var/TimesTen $currentSubsNum $current_dir $verifyOnly $PQBHOME 2>&1)"
    stat=$?
    [ $stat -eq 0 ] &&
        echo_log "done verifying install-def.cfg" ||
        echo_log "problem verifying install-def.cfg"
    echo_log "upgrade output: $out"
    return $stat
}

call_update_config () {

 echo_log "Updating SM configuration"
 # restore config folder to config.prev only if exist

 if [ -d "$PQBHOME/sm/server/root/config/config.prev" ] ; then
    rm -r $PQBHOME/sm/server/root/config/config.prev
    mv -f $PQBHOME/config.prev $PQBHOME/sm/server/root/config &&
    echo_log "configuration files restored to config.prev" ||
    echo_log "configuration files cannot be restored"
 fi

 export current_dir=$(pwd)

 echo_log "Writing $current_dir/install-def.cfg to system log"
 cat $current_dir/install-def.cfg | append_log

 if ! . $PQBHOME/sm.sh; then
    echo "Cannot find SM Java definitions - exiting"
    exit 1
 fi

 local verifyOnly="false"
 

 # call upgrade config function
 local lib="$PQBHOME/sm/server/lib"

 # init old version for install
 if [ ! "$SM_OLD_VERSION" ] ; then
 export SM_OLD_VERSION="$SM_NEW_VERSION"
 export SM_OLD_VERSION_MAJOR="$SM_NEW_VERSION_MAJOR"
 export SM_OLD_VERSION_MINOR="$SM_NEW_VERSION_MINOR" 
 fi

 if [ ! "$currentSubsNum" ]; then
       export currentSubsNum=0
 fi

 echo_log "Current subscribers number: $currentSubsNum"
 chmod 644 $PQBHOME/lib/tt/ttdemo/tterrors.log
 chmod 644 $PQBHOME/lib/tt/ttdemo/ttmesg.log
 
 out="$($PQBJAVA -cp scripts/log4j.jar:scripts/upgrade.jar:$lib/xerces.jar UpgradeSmAndSysOdbcConfig $PQBHOME/sm/server/root $SM_OLD_VERSION_MAJOR $SM_OLD_VERSION_MINOR $SM_NEW_VERSION_MAJOR $SM_NEW_VERSION_MINOR /var/TimesTen $currentSubsNum $current_dir $verifyOnly $PQBHOME 2>&1)"
 stat=$?
 [ $stat -eq 0 ] &&
	echo_log "done invoking configuration update script" ||
	echo_log "problem invoking configuration update script"
    echo_log "script output: $out"
    return $stat
}

check_motd_file(){
   if [ -f "/etc/motd" ] ; then
      local size=$(ls -s /etc/motd | awk '{print $1}')
      if [ $size -eq 0 ] ; then
         return 0
      else
         echo_log "***********************************************************"
         echo_log " Cannot run this script - /etc/motd file exists            "
         echo_log " Please remove the file or move it to another location     "
         echo_log " and run the script again                                  "
         echo_log "***********************************************************"
         return 1
      fi
   else
      return 0
   fi   
}

#
#Hadi Awad "haawad"
#
# ----------------------------------------------------------------------------------
# Demo Kit Installation functions 
# ----------------------------------------------------------------------------------

# SM Configuration File
PROPERTIES_FILE="SM_Configuration.properties"

# pcube Home Directory
PCUBE_USER_HOME_DIRECTORY=""

# Experimental Installation End Marker
END_MARKER="Finished SM DEMO installation sequence"

# SM Configurations Variables
SCE_NAME=""
SCE_IP=""
INSTALLATION_DIRECTORY="/home/demo/sm_home"
PRPC_PASSWORD="p1q2b3"
PCUBE_PASSWORD="pqb12345"

# Parse configuration file and get value of a certain property
parseAndGetValue () {
   VALUE=$(sed '/^\#/d' $PROPERTIES_FILE | grep $1  | tail -n 1 | sed 's/^.*=//;s/^[[:space:]]*//;s/[[:space:]]$//')
   echo $VALUE
}

# Read Configuration file and set config variables
readConfigurationfile () {

   checkIfFileExists $PROPERTIES_FILE || err_and_exit "Demo Kit, SM Configuration File Can't Be Found. $END_MARKER" 12

   SCE_NAME=$(parseAndGetValue 'SM.SCE_NAMES')
   SCE_IP=$(parseAndGetValue 'SM.SCE_IPS')
   INSTALLATION_DIRECTORY=$(parseAndGetValue 'SM.INSTALLATION_DIRECTORY')
   PRPC_PASSWORD=$(parseAndGetValue 'SM.PRPCPASSWORD')
   PCUBE_PASSWORD=$(parseAndGetValue 'SM.PCUBEPASSWORD')
}

# Skip a certian number of lines when reading file
skipLines () {
   for number in $(seq 1 $1)
   do
      read line
   done
}

# Check if a certain file exists
checkIfFileExists () {
   if [ ! -e $1 ];then
	return 1
   fi 
}

# Apply SM Configurations, set it to functon in pull mode and
# define its SCE elements
configSM () {
   
   #Check if file exists, then read file
   p3sm_config_file=""$PCUBE_USER_HOME_DIRECTORY"/sm/server/root/config/p3sm.cfg"
   checkIfFileExists $p3sm_config_file || err_and_exit "Demo Kit, p3sm.cfg File Can't Be Found. $END_MARKER" 12
   exec < $p3sm_config_file

   #Open temp file
   TEMPFILE=$(eval mktemp)
   #Read File
   while read line
   do
      #write to temp file
      VAL=`expr match "$line" 'introduction_mode=*'`
      if [ "$VAL" != 0 ];then
         echo "introduction_mode=pull" >> $TEMPFILE
      elif [ "$line" == "[RDR Server]"  ];then
         echo "[RDR Server]" >> $TEMPFILE
         echo "# whether to run the RDR Server" >> $TEMPFILE
         echo "# (Defult: no)" >> $TEMPFILE
         echo "start=yes" >> $TEMPFILE
         echo " " >> $TEMPFILE
         echo "# the port to listen on for incomming connections" >> $TEMPFILE
         echo "# (Defult: 33001)" >> $TEMPFILE
         echo "port=44000" >> $TEMPFILE
         skipLines 7
      else
         echo "$line" >> $TEMPFILE
         if [ "$line" == "# [SCE.XXX]" ];then
            IP_LIST=(`echo $SCE_IP | tr ';' ' '`)
            NAMES_LIST=(`echo $SCE_NAME | tr ';' ' '`)
            for (( i=0; i<${#IP_LIST[@]}; i++ ))
            do
               echo "  [SCE."${NAMES_LIST[i]}"]" >> $TEMPFILE
               echo "  ip="${IP_LIST[i]}"" >> $TEMPFILE
               echo "  port=14374" >> $TEMPFILE
               echo " " >> $TEMPFILE
            done
         fi
      fi
   done
   mv $TEMPFILE ~pcube/sm/server/root/config/p3sm.cfg
   chmod go=r ~pcube/sm/server/root/config/p3sm.cfg 
}

# Config DHCP Sniffer Leg
configDHCPSniffer () {

   #Check if file exists, then read file
   dhcpsnif_config_file=""$PCUBE_USER_HOME_DIRECTORY"/sm/server/root/config/dhcpsnif.cfg"
   checkIfFileExists $dhcpsnif_config_file || err_and_exit "Demo Kit, dhcpsnif.cfg File Can't Be Found. $END_MARKER" 12
   exec < $dhcpsnif_config_file

   #Open temp file
   TEMPFILE=$(eval mktemp)
   #Read File
   while read line
   do
      #write to temp file
      VAL=`expr match "$line" 'is_cable=*'`
      VAL2=`expr match "$line" 'default_id=*'`
      if [ "$VAL" != 0 ];then
         echo "is_cable=false" >> $TEMPFILE
      elif [ "$VAL2" != 0 ];then
         echo "default_id=ip" >> $TEMPFILE
      elif [ "$line" == "[SCE Sniffer DHCP LEG]"  ];then
         echo "[SCE Sniffer DHCP LEG]" >> $TEMPFILE
         echo "# whether to run the SCE-Sniffer DHCP LEG" >> $TEMPFILE
         echo "# (Default: no)" >> $TEMPFILE
         echo "start=yes" >> $TEMPFILE
         skipLines 3
      else
         echo "$line" >> $TEMPFILE
      fi
   done
   mv $TEMPFILE ~pcube/sm/server/root/config/dhcpsnif.cfg
   chmod go=r ~pcube/sm/server/root/config/dhcpsnif.cfg
}

# Config RADIUS Sniffer Leg
configRADIUSSniffer () {

   #Check if file exists first, then read file
   radsnif_config_file=""$PCUBE_USER_HOME_DIRECTORY"/sm/server/root/config/rad_snif.cfg"
   checkIfFileExists $radsnif_config_file || err_and_exit "Demo Kit, rad_snif.cfg File Can't Be Found. $END_MARKER" 12
   exec < $radsnif_config_file

   #Open temp file
   TEMPFILE=$(eval mktemp)
   #Read File
   while read line
   do
      #write to temp file
      VAL=`expr match "$line" 'packet_types=*'`
      if [ "$VAL" != 0 ];then
         echo "packet_types=accounting-start,accounting-interim,accounting-stop,access-request,access-accept" >>$TEMPFILE
      elif [ "$line" == "[SCE-Sniffer RADIUS LEG]"  ];then
         echo "[SCE-Sniffer RADIUS LEG]" >> $TEMPFILE
         echo "# The following parameter defines whether the SM should run the" >> $TEMPFILE
         echo "# SCE-Sniffer RADIUS LEG at startup. Receives the values: yes, no. " >> $TEMPFILE
         echo "# (Default: no)" >> $TEMPFILE
         echo "start=yes" >> $TEMPFILE
         skipLines 4
      else
         echo "$line" >> $TEMPFILE
      fi
   done
   mv $TEMPFILE ~pcube/sm/server/root/config/rad_snif.cfg
   chmod go=r ~pcube/sm/server/root/config/rad_snif.cfg
}

# Config Shared Memory, called when there is a CM server on same machine
configSharedMem () {

   #check if file exists
   sysctl_config_file="/etc/sysctl.conf"
   checkIfFileExists $sysctl_config_file || err_and_exit "Demo Kit, sysctl.conf File Can't Be Found. $END_MARKER" 12

   #read file
   FOUND=0
   exec < $sysctl_config_file

   #Open temp file
   TEMPFILE=$(eval mktemp)
   #Read File
   while read line
   do
      #write to temp file
      VAL=`expr match "$line" '[#]*kernel.shmmax*'`
      if [ "$VAL" != 0 -a "$FOUND" == 0 ];then
         echo "#"$line"" >> $TEMPFILE
         FOUND=1
      else
         echo "$line" >> $TEMPFILE
      fi
   done
   mv $TEMPFILE /etc/sysctl.conf
   chmod go=r /etc/sysctl.conf
}

# Set perm and temp sizes
setPermAndTempSize () {
   FOUND_PERM=0
   FOUND_TEMP=0
   while read line
   do
      VAL=`expr match "$line" 'PermSize=*'`
      VAL2=`expr match "$line" 'TempSize=*'`
      if [ "$VAL" != 0 ]
      then
         echo "#"$line"" >> $TEMPFILE
         echo "PermSize="$1"" >> $TEMPFILE
         FOUND_PERM=1
      elif [ "$VAL2" != 0 ]
      then
         echo "#"$line"" >> $TEMPFILE
         echo "TempSize="$2"" >> $TEMPFILE
         FOUND_TEMP=1
      else
         echo "$line" >> $TEMPFILE 
      fi
      if [ "$FOUND_PERM" == 1 -a "$FOUND_TEMP" == 1 ]
      then 
         break
      fi
   done
}

# Config perm and temp sizes, called when there is a CM server on same machine
configTimesTen () {

   #check if file exists, then read file
   tt_config_file="/var/TimesTen/sys.odbc.ini"
   checkIfFileExists $tt_config_file || err_and_exit "Demo Kit, sys.odbc.ini File Can't Be Found. $END_MARKER" 12
   exec < $tt_config_file

   #Open temp file
   TEMPFILE=$(eval mktemp)
   #Read File
   while read line
   do
      echo "$line" >> $TEMPFILE 
      if [ "$line" == "[PCube_SM_Repository]" ]
      then
         setPermAndTempSize 100 70
      elif [ "$line" == "[PCube_SM_Local_Repository]" ]
      then
         setPermAndTempSize 20 10
      fi
   done
   mv $TEMPFILE /var/TimesTen/sys.odbc.ini
   chmod go=r /var/TimesTen/sys.odbc.ini
}

# Check previous SM Installation
checkSMInstallation () {
    PCUBE_USER_HOME_DIRECTORY=$( egrep -i "^pcube" /etc/passwd |cut -d ":" -f6 )
    SMInstallationDirectory=""$PCUBE_USER_HOME_DIRECTORY"/sm/server/bin"
    if [ -d "$SMInstallationDirectory" ] 
      then
	echo "DemoKit, SM Installation Found"
      	return 2
    elif [  -n "$PCUBE_USER_HOME_DIRECTORY" ] 
      then
	echo "DemoKit, PCube USer Found"
      	return 1
    else
        echo "DemoKit, No SM Installation Found"
      	return 0
    fi
}

# Uninstall SM Server when found
uninstallSM (){
   
   #check if uninstallation script exists
   checkIfFileExists "uninstall-sm.sh" || err_and_exit "Demo Kit, SM Uninstallation Script Can't Be Found. $END_MARKER" 12

   echo_log "DemoKit, Started SM Uninstallation"
   ./uninstall-sm.sh
}

# Install SM Server and set pcube user passwd
installSM  () {

   #check if installation script exists
   checkIfFileExists "install-sm.sh" || err_and_exit "Demo Kit, SM Installation Script Can't Be Found. $END_MARKER" 12

   echo_log "DemoKit, Started SM Installation"
   ./tt-sysconf.sh 
   rm -rf /etc/motd
   if [ "$1" == "PCUBE_FOUND" ] 
   then
      ./install-sm.sh -o
   else
      ./install-sm.sh -d "$INSTALLATION_DIRECTORY"
   fi

}

# Apply SM Server Configurations
applySMConfigs () {

   #In clean installation cases, this var won't be populated correctly 
   PCUBE_USER_HOME_DIRECTORY=$( egrep -i "^pcube" /etc/passwd |cut -d ":" -f6 )

   echo_log "DemoKit, Setting pcube user password"
   echo $PCUBE_PASSWORD | passwd --stdin pcube

   echo_log "DemoKit, Configuring SM"
   configSM

   echo_log "DemoKit, Configuring DHCP Sniffer"
   configDHCPSniffer

   echo_log "DemoKit, Configuring RADIUS Sniffer"
   configRADIUSSniffer

   if [ "$1" == "true" ]
   then
       echo_log "DemoKit, SM and CM were installed on same machine"
       echo_log "DemoKit, Configuring SM Database"
       configTimesTen

       echo_log "DemoKit, Configuring Shared Memory"
       configSharedMem
   fi

   echo_log "DemoKit, Restarting SM, setting PRPC user password and loading config"
   su - pcube -c "
   cd ~pcube/sm/server/bin/;
   ./p3sm --restart --wait;
   ./p3rpc --set-user --username=pcube --password="$PRPC_PASSWORD";
   ./p3sm --load-config;"
}


check_distribution() {
   if is_linux ; then
			# Import the linux def file for using the java and TT file names declaration
			import_linuxdef
			if [ -z $1 ] || [ $1 != "true" ] ; then
					if is_linux_64bit ; then
							if [ ! -f $java_file_64 ] ; then
									err_and_exit "Cannot find 64-bit JRE Installation files. Run install-sm from 64-bit RedHat distribution file" 1
							fi
					fi
			fi

			if [ -z $2 ] || [ $2 != "true" ] ; then
					if is_linux_64bit ; then
							if [ ! -f $self_extracting_tt_file_64 ] ; then
									err_and_exit "Cannot find 64-bit SM Database installation files. Run install-sm from 32-bit RedHat distribution file" 1
							fi
					fi
			fi
	fi

}


import_linuxdef() {
        if ! . linux-def.sh; then
                echo "Cannot find Linux common definitions - exiting"
                echo "run install-sm from the RedHat distribution file"
                exit 1
        fi
}






