#!/bin/sh

# ./rc <command>
#      start           : starts zxtm
#      stop            : stops zxtm
#      restart         : restarts zxtm
#      reload          : sends a HUP to zxtm

if [ -z "$ZEUSHOME" ]
then
  cd `dirname $0`/..
  ZEUSHOME=`pwd`
  export ZEUSHOME
fi

ZXTM_PIDFILE=$ZEUSHOME/zxtm/internal/pid
GDBMON_PIDFILE=$ZEUSHOME/zxtm/internal/gdbmonpid
SYSD_PIDFILE=$ZEUSHOME/zxtm/internal/sysdpid
PROCMON_PIDFILE=$ZEUSHOME/zxtm/internal/procmonpid
PROGRAM="Stingray Traffic Manager"
PROCMON="Stingray Watchdog"
ZEUSGDBMON=zeus.gdbmon
PLATFORM=`uname`
# The best available approximation to a portable way to get ps to say
# whether a process ID is currently live ... only MacOSX needs a tweak.
case $PLATFORM in
    Darwin|MacOSX|Rhapsody) dashp='-w -w -w -p';;
    Linux|FreeBSD) dashp='-w -w -w -f -p';;
    *) dashp='-f -p';;
esac

# Usage: live_pid pid [prog_name]
live_pid()
{
    PID=$1
    PROCNAME=`basename $2`

    ps $dashp $PID 2>/dev/null | sed -e "s@.*$PID .*$PROCNAME@MATCH@" |grep '^MATCH' >/dev/null 2>&1
    if [ $? = 0 ] ; then
        return 0;
    fi

    # On Solaris, try without the -f
    if [ $PLATFORM = "SunOS" ] ; then
        # without the -f we only get 8 chars of the program name
        PROC8NAME=`echo $PROCNAME | sed -e 's/\(........\).*/\1/'`;
        ps -p $PID 2>/dev/null | sed -e "s@.*$PID .*$PROC8NAME@MATCH@" |grep '^MATCH' >/dev/null 2>&1
        if [ $? = 0 ] ; then
            return 0;
        fi
    fi

    return 1
}

unrun() # unrun pidfile program-name
{
    # Succeeds iff the process isn't running.
    if [ -f "$1" ]
    then
        PID=`sed -e 's/ .*//' < "$1"`
        PROGNAME=`sed -e 's/[0-9]* //' < "$1"`
        if [ "x$PROGNAME" = "x$PID" ]; then
            # Old style, PID-only pidfile
            PROGNAME=
        fi
        if live_pid $PID $PROGNAME
        then
            echo "$2 already running: $PID"
            return 1
        fi
        rm -f "$1"
    fi
    return 0
}

startgdbmon()
{
    GDBPATH=`which gdb 2>/dev/null`
    if [ -x $GDBPATH ]
    then
       # Starts gdbmon
       unrun "$GDBMON_PIDFILE" "GDBMON" || return 0
       $ZEUSHOME/zxtm/bin/$ZEUSGDBMON && \
          echo "Started gdb watchdog"
    else
       echo "WARNING: 'gdb' not found; cannot start gdb watchdog."
       echo "Please install the 'gdb' program to get full debug output."
    fi
}

startprocmon()
{
    unrun "$PROCMON_PIDFILE" "$PROCMON" || return 0
    $ZEUSHOME/zxtm/bin/procmon -q 2>>$ZEUSHOME/zxtm/log/procmon >>$ZEUSHOME/zxtm/log/procmon &
    # procmon restarts itself with miniperl
    echo $! $ZEUSHOME/perl/miniperl > $PROCMON_PIDFILE
}

startsw()
{
    # Lets try to enable core files before we start
    # id returns uid=0(root) gid=1(other)
    ID=`id | sed -e 's/uid=[0-9]*(\([^)]*\)).*/\1/'`
    case $ID in
       root)
          ulimit -c unlimited 2>/dev/null
          case $PLATFORM in
             SunOS)
                COREADM=`which coreadm 2>/dev/null`
                if [ -x $COREADM ]
                then
                   $COREADM -i core -e process -e proc-setid
                fi;;
             FreeBSD)
                /sbin/sysctl -w kern.sugid_coredump=1 kern.coredump=1 >/dev/null 2>&1
                ;;
          esac;;
    esac
    # Starts sw (if possible)
    unrun "$ZXTM_PIDFILE" "$PROGRAM" || return 0
    if [ -f $ZEUSHOME/zxtm/bin/zeus.zxtm.debug ]
    then
      $ZEUSHOME/zxtm/bin/zeus.zxtm.debug $ZXTM_DEBUG_OPTS && \
         echo "Started development zeus.zxtm"
      startgdbmon
    else
      $ZEUSHOME/zxtm/bin/zeus.zxtm || return 1
      startprocmon
    fi
    return 0
}

stop_pid() # stop pidfile process-name
{
    # Succeeds if no process running on return.
    if [ -f "$1" ]
    then
        PID=`sed -e 's/ .*//' < "$1"`
        PROGNAME=`sed -e 's/[0-9]* //' < "$1"`
        if [ "x$PROGNAME" = "x$PID" ]; then
            # Old style, PID-only pidfile
            PROGNAME=
        fi

        if live_pid $PID $PROGNAME
        then
            # if $PID will listen to our signals, kill it.
            if kill -0 $PID 2>/dev/null
            then
                # Have a go at killing $PID
                kill $PID
                # Now wait for it to die, or fail because it didn't:
                # but keep the wait brief if at all possible ...

                for secs in 1 1 2 3 5 8 5 3 2 1 0
                do
                    if kill -0 $PID 2>/dev/null
                    then [ $secs -eq 0 ] || sleep $secs # process still alive
                    else
                        echo $2 stopped
                        rm -f $1
                        return 0
                    fi
                done

                echo Failed to kill process $PID.
                echo It is still running your $2.
                return 1
            else
                echo I cannot send signals to process $PID.
                echo It is still running your $2.
                return 1
            fi
        else
            echo "$2 process $PID was already dead."
            rm -f "$1"
        fi
    fi
    return 0
}

hup_pid() # hup_pid pidfile process-name
{
    if [ -f "$1" ]
    then
        PID=`sed -e 's/ .*//' < "$1"`
        PROGNAME=`sed -e 's/[0-9]* //' < "$1"`
        if [ "x$PROGNAME" = "x$PID" ]; then
            # Old style, PID-only pidfile
            PROGNAME=
        fi

        if live_pid $PID $PROGNAME
        then
            # if $PID will listen to our signals, HUP it.
            if kill -HUP $PID 2>/dev/null
            then
                echo Reloading $2 configuration.
                return 0
            else
                echo Could not tell $2 to reload configuration.
                return 1
            fi
        else
            echo $2 process $PID is dead.
            rm -f "$1"
            return 1
        fi
    else
        echo $2 is not running.
        return 1
    fi
}

sendemails()
{
    if [ -x "$ZEUSHOME/zxtm/bin/notify" ] ; then
        $ZEUSHOME/zxtm/bin/notify 2>/dev/null >/dev/null # send any emails
    fi
}

ncssinstall()
{
    if [ -x "$ZEUSHOME/zxtm/bin/ncssinstall" ] && [ -f "/etc/zxtm-version" ] && [ `id -u` -eq 0 ]; then
        # If new nCipher software has been uploaded, unpack and configure it
        $ZEUSHOME/zxtm/bin/ncssinstall || true
    fi
}

checkbranding()
{
    # Copy the branding file across if it exists in /etc and doesn't
    # exist in the zxtmadmin directory
    if [ ! -f "$ZEUSHOME/zxtmadmin/lang/_default/branding" -a -f "/etc/zeus.branding.factory" ] ; then
        cp "/etc/zeus.branding.factory" "$ZEUSHOME/zxtmadmin/lang/_default/branding" || true
    fi
}

case "$1" in

    'start')
        checkbranding
        ncssinstall
        startsw
        exit $?
        ;;

    'stop')
        stop_pid "$PROCMON_PIDFILE" "$PROCMON"
        stop_pid "$ZXTM_PIDFILE" "$PROGRAM"
        stop_pid "$GDBMON_PIDFILE" "GDBMON"
        # emails are sent by zxtm itself
        exit $?
        ;;

    'restart')
        checkbranding
        stop_pid "$GDBMON_PIDFILE" "GDBMON"
        stop_pid "$PROCMON_PIDFILE" "$PROCMON"
        stop_pid "$ZXTM_PIDFILE" "$PROGRAM" && \
            ncssinstall && \
            startsw && echo Restarted $PROGRAM
        exit $?
        ;;

    'reload')
        hup_pid "$ZXTM_PIDFILE" "$PROGRAM" && \
        hup_pid "$SYSD_PIDFILE" "$PROGRAM sysd"
        exit $?
        ;;

    *)
        echo "usage: $0 {start|stop|restart|reload}"
        ;;
esac

exit 1
