#!/bin/bash
#
# chkconfig: 2345 90 12
# description: Jumpgate Agent daemon for Centos6 - Connects to CDP Control Plane
# processname: jumpgate-agent
### BEGIN OF INIT INFO
# Required-Start: network-online.target
# Default-Start: 2 3 4 5

# Get function from functions library
. /etc/init.d/functions
LOCK=/var/lock/subsys/jumpgate-agent
TIMESTAMP=/root/timestamp.txt
touch $TIMESTAMP
chmod +x $TIMESTAMP
# Start the service jumpgate-agent
start() {
        if [ ! -f "$LOCK" ];then
          daemon /etc/jumpgate/run.sh 2>&1
          RETVAL=$?

          if [ $RETVAL -eq 0 ]; then
            echo `date` > $TIMESTAMP
            touch $LOCK
          fi
        fi
        return $RETVAL
}

# Stop the service jumpgate-agent
stop() {
        if [[ $(ps aux | grep "/usr/bin/jumpgate-agent --config=/etc/jumpgate/config.toml" | grep -v grep | wc -l) -gt 0 ]]; then
          sudo kill $(ps aux | grep "/usr/bin/jumpgate-agent --config=/etc/jumpgate/config.toml" | grep -v grep | awk '{print $2}')
          RETVAL=$?
          if [ $RETVAL -eq 0 ];then
            echo `date` > $TIMESTAMP
            rm -f $LOCK
          fi
          return $RETVAL
        fi
}

status() {
        ts=$(cat $TIMESTAMP)
        if [[ $(ps aux | grep "/usr/bin/jumpgate-agent --config=/etc/jumpgate/config.toml" | grep -v grep | wc -l) -eq 0 ]]; then
          echo "Jumpgate Agent is not running since $ts"
        else
          echo "Jumpgate Agent is running since $ts"
        fi
}

### main logic ###
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  status)
        status
        ;;
  restart|reload|condrestart)
        stop
        start
        ;;
  *)
        echo $"Usage: $0 {start|stop|restart|reload|status}"
        exit 1
esac
exit $?
