#!/bin/sh
# $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
source /usr/share/DTBrand.sh

# Source function library. 
# Do not remove under pain of death!
. /lib/lsb/init-functions
ulimit -s 10240
ulimit -c unlimited

### 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}"

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"

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

start () {
        # Start daemon.
        echo -n $"Checking $SERVICE_DISPLAY_NAME drivers: "
        driver_start
        RETVAL=$?
        if [ "$RETVAL" = "0" ]; then
            echo "[ OK ]"
        else
            echo "[ FAILED ]"
        fi
        echo -n $"Starting $SERVICE_DISPLAY_NAME: "
        daemon_start "$1"
        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 "$DAEMON_BINARY_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 $DAEMON_BINARY_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 $DAEMON_BINARY_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 $DAEMON_BINARY_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 $DAEMON_BINARY_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
    else 
        # Start daemon using standard daemon startup routine
        start_daemon $(which "$DAEMON_BINARY_NAME")
        RETVAL=$?
        if [ $RETVAL = 0 ]; then
            echo [ OK ]
        else
            echo [ FAILED ]
        fi
    fi
}

stop () {
    # Stop daemon.
    echo -n $"Stopping $SERVICE_DISPLAY_NAME: "
    daemon_stop
    RETVAL=$?
    if [ $RETVAL = 0 ]; then
        rm -f /var/lock/subsys/$DAEMON_BINARY_NAME 
        echo [ OK ]
    else
        echo [ FAILED ]
    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
        echo "[ OK ]"
    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 () {
    killproc "$DAEMON_BINARY_NAME"
}

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 $"${program} (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 $"${program} dead but pid file exists"
            return 2
        fi
    fi

    if [ -f /var/lock/subsys/${program} ]; then
       echo $"${program} dead but subsys locked"
       return 3
    fi
    echo $"${program} 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/dblt && "$0" restart
       ;;
    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:
