#!/bin/sh
#
# gnservice     Glam daemon the communicates with keys.
#
# chkconfig: 345 10 99
# description: Glam daemon the communicates with keys.
# processname: java
# pidfile: /var/run/hnmd.pid
# config: /etc/glam/glam.properties
. /etc/init.d/functions

APP_NAME=gnservice
PROD_NAME=glam
APP_HOME=/usr/local/glam
DAEMON_HOME=$APP_HOME/$APP_NAME
DAEMON_NAME=gnservice
LOG_DIR=/var/log/glam

PS_CMD="ps auwwwx"
LOCK_DIR=/var/lock/subsys/

if [ ! -f $DAEMON_HOME/bin/$DAEMON_NAME.jar ]; then
    printf "gnservice Installation is incomplete.\n"
    exit -1
fi

case "$1" in
  start)
        if [ ! -d $LOG_DIR ]; then
                mkdir -p $LOG_DIR
        fi

        pid=`$PS_CMD | sed -n "/$DAEMON_NAME.jar/{/grep/!p;}" | awk '{print $2}'`
        #pid=`ps -aefw | grep "$DAEMON_NAME.jar" | grep -v " grep " | awk '{print $2}'`
        if [ "$pid" != "" ]; then
                printf "Daemon already running...\n"
                exit 3
        fi

        # Copy previous stdout log file
        cp -f $LOG_DIR/$DAEMON_NAME.log $LOG_DIR/$DAEMON_NAME.log.prev

        printf "Starting $DAEMON_NAME...\n"
        `cd $DAEMON_HOME; nohup ./run > $LOG_DIR/$DAEMON_NAME.log 2>&1 &` && echo_success || echo_failure
        [ $? -eq 0 ] && touch $LOCK_DIR/$PROD_NAME-$DAEMON_NAME
        ;;
  stop)
        printf "Stopping $DAEMON_NAME...\n"
        pid=`$PS_CMD | sed -n "/$DAEMON_NAME.jar/{/grep/!p;}" | awk '{print $2}'`

        if [ "" != "$pid" ]; then
                kill -9 $pid && echo_success || echo_failure
        else
                printf "$DAEMON_NAME is not running\n"
        fi
        [ $? -eq 0 ] && rm -f $LOCK_DIR/$PROD_NAME-$DAEMON_NAME
        ;;
  status)
        pid=`$PS_CMD | sed -n "/$DAEMON_NAME.jar/{/grep/!p;}" | awk '{print $2}'`
        if [ "$pid" == "" ]; then
                printf "$DAEMON_NAME Daemon is stopped.\n"
                exit 3
        fi
        kill -0 $pid >/dev/null 2>&1
        if [ $? -eq 0 ]
        then printf "$DAEMON_NAME Daemon (pid %s) is running...\n" "$pid"
             exit 0
        fi
        printf "$DAEMON_NAME Daemon is stopped\n"
        exit 3
        ;;
  restart)
        $0 stop
        sleep 5
        $0 start
        ;;
  reload)
        $0 stop
        sleep 5
        $0 start
        ;;
  condrestart)
       if [ -f $LOCK_DIR/$PROD_NAME-$DAEMON_NAME ]; then
            $0 stop
            sleep 5
            $0 start
        fi
        ;;
*)
        printf "Usage: %s { start | stop | status | restart | condrestart }\n" "$0"
        exit 1
        ;;
esac
exit 0
