#!/bin/bash
# $Id: DT 596 2007-08-31 19:31:06Z mschultheiss@doubletake.com $
# dblt This script starts and stops the DT daemon
#
# chkconfig: 345 24 75
# description: Data replication and high-availability service

# Get branding-related environment
# Bug# 1757 Changed by @IndusaDevTeam
source /etc/DTBrand.sh

# Source function library. 
# Do not remove under pain of death!
. /lib/lsb/init-functions

shopt -s expand_aliases

ulimit -s 10240
ulimit -c unlimited
# For RHEL:
DAEMON_COREFILE_LIMIT=unlimited
export DAEMON_COREFILE_LIMIT

### BEGIN INIT INFO
# Provides:          DT
# Required-Start:    $local_fs $syslog $network $remotefs
# Required-Stop:     $local_fs $syslog $network $remotefs
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 6
# Short-Description: Data replication and high-availability service
# Description:       Start DT to replicate data and provide high-availability
### END INIT INFO

SCRIPT=${0##*/}
SCRIPT="$SCRIPT service script"
SERVICE_DISPLAY_NAME="${DTBRAND_DISPLAY_NAME_IN_TEXT_UI}"
DAEMON_BINARY_NAME="${DTBRAND_DAEMON_BINARY_NAME}"
INSTALL_SUBDIR="${DTBRAND_PATH_SUBDIR}"
RPM_PACKAGE_NAME="${DTBRAND_RPM_PACKAGE_NAME}"
EULA_FILE="/etc/${INSTALL_SUBDIR}/Read_And_Accepted_Double-Take_Software_End_User_License_Agreement"

PATH="$PATH":/usr/bin:/usr/local/bin
CONFIG_DIR="/etc/${INSTALL_SUBDIR}"

# SCR00227599: Added by @IndusaDevTeam
ACTIVATION_CODE="ActivationCode"
CONF_FILE="${CONFIG_DIR}/${DAEMON_BINARY_NAME}.conf"
DT_RUNMODEFILE_GDB="${CONFIG_DIR}/runmode.gdb"
DT_RUNMODEFILE_MCHECK="${CONFIG_DIR}/runmode.mcheck"
DT_RUNMODEFILE_DUMA="${CONFIG_DIR}/runmode.duma"
DT_GDB_COMMANDFILE="${CONFIG_DIR}/commands.gdb"
DT_RUNMODEFILE_MTRACE="$CONFIG_DIR/runmode.mtrace"
DT_RUNMODEFILE_VAL_MEMCHK="$CONFIG_DIR/runmode.val_memchk"
DT_RUNMODEFILE_VAL_MEMLEAK="$CONFIG_DIR/runmode.val_memleak"
DT_RUNMODEFILE_VAL_MASSIF="$CONFIG_DIR/runmode.val_massif"

# The next few functions report problems, including the script name and the
# current process ID, to the system log (and sometimes stderr as well).  The
# default facility and priority are "user" and "notice".

grumble () {
    # Complain about the arguments to the system log.
    logger -i -t "$SCRIPT" "$*"
}

squawk () {
    # Screech the arguments to stderr and the system log.
    logger -i -s -t "$SCRIPT" "$*"
}

howl () {
    # Shout the arguments to stderr and the system log with a scary prefix.
    logger -i -s -p user.warning -t "$SCRIPT" "WARNING: $*"
}

load_dt_kernel_modules () {
    DTInit.sh -l
}

load_dtrep_settings () {
    DTInit.sh -s
}

mount_and_register_file_systems () {
    DTInit.sh -m -a
}

unregister_and_unmount_file_systems () {
    DTInit.sh -u -d
}

# Added by @IndusaDevTeam
# SCR00227599
generate_key_in_correct_format () {
   if [ -f $CONF_FILE ]; then ##SCR00232887
       ENTRY=$(grep $ACTIVATION_CODE $CONF_FILE)
       STRLEN=$(expr length "$ENTRY")

       KEYNAMELEN=$(expr length "$ACTIVATION_CODE")
       let KEYNAMELEN=$KEYNAMELEN+2

       ENTRY=$(expr substr "$ENTRY" $KEYNAMELEN $STRLEN)
       KEYLEN=$(expr length "$ENTRY")
       
       export ENTRY
       if [ "$KEYLEN" -gt "24" ]; then
           /usr/bin/DTInit.sh -S 
       fi
       unset ENTRY
   fi
}

# Must run as root. Added by @IndusaDevTeam
if [ "$(id -u)" != "0" ]; then
    echo "$SCRIPT:" $"error:" \
         $"superuser privileges required to run this program" >&2
    exit 2
fi

start () {
        # Added by @IndusaDevTeam
        # SCR00227599 : Generate 24 Chars Activation Code in correct format
        generate_key_in_correct_format

        SESTATUS=$(which sestatus 2>/dev/null)
        if [ -n "$SESTATUS" ]; then
            SELSTATUS=$(sestatus | grep "enforcing" || true)
            if [ -n "$SELSTATUS" ]; then
                howl $"$SERVICE_DISPLAY_NAME drivers cannot be configured because SELinux is enabled and enforcing. Disable it or set to permissive mode."
                exit 1
            fi
        fi

        # Start daemon.
        echo -n $"Checking $SERVICE_DISPLAY_NAME drivers: "
        driver_start
        RETVAL=$?
        if [ "$RETVAL" = "0" ]; then
            log_success_msg
        else
            log_failure_msg
        fi
        echo -n $"Starting $SERVICE_DISPLAY_NAME: "
        daemon_start "$1"
#DTMS         mgmt_start
        RETVAL=$?
        echo
        if [ $RETVAL = 0 ]; then
            touch /var/lock/subsys/$DAEMON_BINARY_NAME
        fi
}

driver_start () {
    # Load the kernel modules.
    if ! load_dt_kernel_modules; then
        howl "$SERVICE_DISPLAY_NAME drivers not loaded; replication disabled"
        return 1
    fi

    # Wait for the user/kernel space communications link to come up.
    if ! MSG=$(DTRepWait 2>&1); then
        howl "$MSG; replication disabled"
        return 1
    fi

    # Load dtrep settings
    load_dtrep_settings || :

    # We don't check the return status of the following function because the
    # daemon can work just fine without any replication sources (the desired
    # configuration may have only targets).
    mount_and_register_file_systems
}

daemon_start () {
   
    if [ "$1" = "GDB" -o -f "$DT_RUNMODEFILE_GDB" ]; then
        squawk "Starting $SERVICE_DISPLAY_NAME in the gdb debugger."
        cat > $DT_GDB_COMMANDFILE <<EOF
            set args -d
            define hook-stop
              bt
            end
            echo ----------------------------------------------------------------------\n
            echo Debugging tips:\n
            echo   Use kill -STOP <pid> to break into debugger.\n
            echo   Use debugger command 'quit' to stop DT.\n
            echo   The <pid> is after 'LWP' in the first 'New thread...' message below.\n
            echo ----------------------------------------------------------------------\n
            start
EOF
        gdb $DAEMON_BINARY_NAME -x $DT_GDB_COMMANDFILE
        sleep 5
    elif [ "$1" = "MTRACE" -o -f "$DT_RUNMODEFILE_MTRACE" ]; then
        squawk "Starting $SERVICE_DISPLAY_NAME in gdb with mtrace memory leak tracing."
        cat > $DT_GDB_COMMANDFILE <<EOF
            set args -d -d
            set env MALLOC_TRACE=/var/log/DT/memtrace.txt
            define hook-stop
              bt
            end
            echo ----------------------------------------------------------------------\n
            echo Debugging tips:\n
            echo   Use kill -STOP <pid> to break into debugger.\n
            echo   Use debugger command 'quit' to stop DT.\n
            echo   The <pid> is after 'LWP' in the first 'New thread...' message below.\n
            echo ----------------------------------------------------------------------\n
            start
EOF
        gdb $DAEMON_BINARY_NAME -x $DT_GDB_COMMANDFILE
        sleep 5
    elif [ "$1" = MCHECK -o -f "$DT_RUNMODEFILE_MCHECK" ]; then
        squawk "Starting $SERVICE_DISPLAY_NAME in gdb with mcheck memory checking."
        cat > $DT_GDB_COMMANDFILE <<EOF
            set args -d
            set env MALLOC_CHECK_=2
            define hook-stop
              bt
            end
            echo ----------------------------------------------------------------------\n
            echo Debugging tips:\n
            echo   Use kill -STOP <pid> to break into debugger.\n
            echo   Use debugger command 'quit' to stop DT.\n
            echo   The <pid> is after 'LWP' in the first 'New thread...' message below.\n
            echo ----------------------------------------------------------------------\n
            start
EOF
        gdb $DAEMON_BINARY_NAME -x $DT_GDB_COMMANDFILE
        sleep 5
    elif [ "$1" = "DUMA" -o -f "$DT_RUNMODEFILE_DUMA" ]; then
        squawk "Starting $SERVICE_DISPLAY_NAME in gdb with DUMA (ElectricFence fork) memory checking."
        cat > $DT_GDB_COMMANDFILE <<EOF
            set args -d
            set env LD_PRELOAD=libduma.so.0.0
            set env LD_BIND_NOW="not empty is good for debugging"
            set env DYLD_INSERT_LIBRARIES=libduma.dylib
            set env DYLD_FORCE_FLAT_NAMESPACE=1
            echo ----------------------------------------------------------------------\n
            echo Debugging tips:\n
            echo   Use kill -STOP <pid> to break into debugger.\n
            echo   Use debugger command 'quit' to stop DT.\n
            echo   The <pid> is after 'LWP' in the first 'New thread...' message below.\n
            echo ----------------------------------------------------------------------\n
            run
EOF
        gdb $DAEMON_BINARY_NAME -x $DT_GDB_COMMANDFILE
        sleep 5
    elif [ "$1" = "VAL_MEMCHK" -o -f "$DT_RUNMODEFILE_VAL_MEMCHK" ]; then
        PATH=$PATH:/opt/valgrind/bin
        VALGRIND=$(which valgrind)
        if [ -n "$VALGRIND" ]; then
           squawk "Starting $SERVICE_DISPLAY_NAME in Valgrind with general checking."
           valgrind --track-origins=yes --log-file=/var/log/${INSTALL_SUBDIR}/valgrind-%p.log --db-attach=yes --db-command="gdb $DAEMON_BINARY_NAME %p" $DAEMON_BINARY_NAME -d
           sleep 5
        else
            echo "valgrind could not be located, modify the path in /etc/init.d/DT or install valgrind"
        fi
    elif [ "$1" = "VAL_MASSIF" -o -f "$DT_RUNMODEFILE_VAL_MASSIF" ]; then
        PATH=$PATH:/opt/valgrind/bin
        VALGRIND=$(which valgrind)
        if [ -n "$VALGRIND" ]; then
           squawk "Starting $SERVICE_DISPLAY_NAME in Valgrind with massif memory profiling."
           valgrind --tool=massif --stacks=no $DAEMON_BINARY_NAME -d
           sleep 5
        else
            echo "valgrind could not be located, modify the path in /etc/init.d/DT or install valgrind"
        fi
    elif [ "$1" = "VAL_MEMLEAK" -o -f "$DT_RUNMODEFILE_VAL_MEMLEAK" ]; then
        PATH="$PATH":/opt/valgrind/bin
        VALGRIND=$(which valgrind)
        if [ -n "$VALGRIND" ]; then
           squawk "Starting $SERVICE_DISPLAY_NAME in Valgrind with memory leak checking."
           $VALGRIND --db-attach=no --log-file="/var/log/${INSTALL_SUBDIR}/valgrind-%p.log" --leak-check=full $DAEMON_BINARY_NAME -d
           sleep 5
        else
            echo "valgrind could not be located, modify the path in /etc/init.d/DT or install valgrind"
        fi
    else 
        # Start daemon using standard daemon startup routine
        start_daemon $(which "$DAEMON_BINARY_NAME")
        RETVAL=$?
        if [ $RETVAL = 0 ]; then
            log_success_msg
        else
            log_failure_msg
        fi
    fi
}

#DTMS mgmt_start() {
#DTMS     (cd /usr/lib/DT/DTMgmtSvc && \
#DTMS         LD_LIBRARY_PATH=/usr/lib/DT/lib \
#DTMS         PATH=/usr/lib/DT/bin:$PATH \
#DTMS         /usr/lib/DT/bin/ruby \
#DTMS         /usr/lib/DT/DTMgmtSvc/script/server -d -p 6325 -e production
#DTMS     ) >/usr/lib/DT/DTMgmtSvc/log/production.log 2>&1
#DTMS }

stop () {
    # Stop daemon.
    echo -n $"Stopping $SERVICE_DISPLAY_NAME: "
    daemon_stop
#DTMS     mgmt_stop
    RETVAL=$?
    if [ $RETVAL = 0 ]; then
        rm -f /var/lock/subsys/$DAEMON_BINARY_NAME 
        log_success_msg
    else
        log_failure_msg
    fi
}

driver_stop () {
    echo -n $"Stopping $SERVICE_DISPLAY_NAME drivers: "
    # Unregister and unmount DTFS file systems.
    if ! unregister_and_unmount_file_systems; then
        howl "$SERVICE_DISPLAY_NAME drivers may already have been stopped;"\
             "if not, kernel modules may not unload due to still-mounted or" \
             "still-registered DTFS file systems"
    else
        log_success_msg
    fi

    # Unload the kernel modules.  modprobe does not make noise or exit
    # nonzero if it is asked to remove modules that aren't loaded (unlike
    # rmmod).
    #
    # We don't bother to unlink the modules from /lib/modules/$(uname -r) or
    # re-run depmod -a; it doesn't seem necessary and would waste time on
    # shutdown.  Unloading is still useful, though, particularly if the
    # user requests a daemon restart.  (If there was a problem loading them,
    # he or she might have fixed it.)
    #
    # Some kernels don't support unloading kernel modules, but that's not
    # the case for Red Hat Enterprise Linux 4.
    modprobe -r dtrep dtloop dtfs > /dev/null 2>&1 || true
}

daemon_stop () {
    if [ -f /etc/debian_version ]; then
      /sbin/start-stop-daemon --stop --quiet --oknodo --name "$DAEMON_BINARY_NAME" --pidfile /var/run/${DAEMON_BINARY_NAME}.pid --retry 15
    else
      killproc "$DAEMON_BINARY_NAME"
    fi
}


#DTMS mgmt_stop() {
#DTMS     kill -INT $(cat /usr/lib/DT/DTMgmtSvc/tmp/pids/server.pid )
#DTMS }

status () {
    local program=${1##*/}
    local PID
    if [ 0 = "$#" ]; then
       echo $"Usage: status {program}"
       return 1
    fi
  
    PID=$(pidof -o $$ -o $PPID -o %PPID -x $1 || \
            pidof -o $$ -o $PPID -o %PPID -x ${program})
    if [ -n "$PID" ]; then
        echo $"${SERVICE_DISPLAY_NAME} (pid $PID) is running..."
        return 0
    fi

    if [ -f  /var/run/${program}.pid ]; then
        read PID < /var/run/${program}.pid
        if [ -n "$PID" ]; then
            echo $"${SERVICE_DISPLAY_NAME} dead but pid file exists"
            return 2
        fi
    fi

    if [ -f /var/lock/subsys/${program} ]; then
       echo $"${SERVICE_DISPLAY_NAME} dead but subsys locked"
       return 3
    fi
    echo $"${SERVICE_DISPLAY_NAME} is stopped"
    return 4
}

# See if they have agreed to the EULA and Maintenance conditions
if [ ! -f "$EULA_FILE" ]; then
    squawk "${DTBRAND_PRODUCT_NAME} End User License Agreement not accepted! Run DTSetup."
    exit 0;
fi

# See if the daemon is installed.
if ! which "$DAEMON_BINARY_NAME" >/dev/null 2>&1; then
    grumble "$DAEMON_BINARY_NAME is not in execution path; exiting"
    exit 0
fi

# Assume success until we learn otherwise.
RETVAL=0

# See how we were called.
case "$1" in
    start)
        start $2
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start $2
        ;;
    halt)
        stop
        driver_stop
        ;;        
    reload)
        stop
        driver_stop
        start $2
        ;;
    condrestart)
       test -e /var/lock/subsys/DT && "$0" restart #Bug 4536 Changed by @IndusaDevTeam
       ;;
    status)
        status "$DAEMON_BINARY_NAME"
        RETVAL=$?
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|halt|reload|status|condrestart}"
        echo
        echo "    start   - initiate drivers, process driver config and start daemon"
        echo "    stop    - stops the daemon process only, driver config left intact"
        echo "    restart - perform a stop, followed by a start"
        echo "    halt    - stop daemon, remove driver config and unload drivers" 
        echo "    reload  - performs a halt, followed by a start"
        echo "    status  - outputs whether daemon is running"
        echo "    condrestart - performs a restart if daemon is already running"
        RETVAL=1
        ;;
esac

exit $RETVAL

# vim:set ai et ts=4 sw=4 tw=80:
