### BEGIN INIT INFO
# Provides:          nano_agent
# Required-Start:    $local_fs $network $named $time $syslog
# Required-Stop:     $local_fs $network $named $time $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Description:       Check Point Linux Nano Agent
### END INIT INFO

START=99
SCRIPT_NAME="cp-nano-watchdog"
SCRIPT="/etc/cp/watchdog/${SCRIPT_NAME} --smb"

PIDFILE=/var/run/nano_agent.pid
LOGFILE=/var/log/nano_agent.log
SERVICE_NAME=nano_agent

if [ ! -d /etc/cp ]; then
	ln -sf /storage/nano_agent/etc/cp /etc/cp
fi
if [ ! -d /usr/lib/cpnano ]; then
	ln -sf /storage/nano_agent/usr/lib/cpnano /usr/lib/cpnano
fi
if [ ! -f /usr/sbin/cpnano ]; then
	ln -sf /etc/cp/scripts/cp-nano-agent-ctl.sh /usr/sbin/cpnano
fi
if [ ! -f /pfrm2.0/bin/nano_pidof ]; then
cat << EOF > /pfrm2.0/bin/nano_pidof
#!/bin/sh
pidof \`basename "\$1"\`
EOF
	chmod +rx /pfrm2.0/bin/nano_pidof
fi

mkdir -p /var/log/nano_agent
mkdir -p /storage/tmp

start() {
  if [ -f $PIDFILE ] && [ -s $PIDFILE ] && kill -0 $(cat $PIDFILE); then
    echo 'Service already running' >&2
    return 1
  fi
  echo 'Starting service ' $SERVICE_NAME >&2
  $SCRIPT > /dev/null 2>&1 &
  echo $! > $PIDFILE

  sleep 2
  PID=$(cat $PIDFILE)
  if [ -d "/proc/${PID}" ]; then
    echo "$SERVICE_NAME is now running, the PID is $PID"
  else
    echo ''
    echo "Error! Could not start $SERVICE_NAME!"
  fi
}

stop() {
  if [ ! -f "$PIDFILE" ] || ! kill -0 $(cat "$PIDFILE"); then
    echo 'Service not running' >&2
    return 1
  fi
  echo 'Stopping service $SERVICE_NAME' >&2
  kill -15 $(cat "$PIDFILE") && rm -f "$PIDFILE"
  echo 'Service stopped' >&2
}

status() {
    printf "%-50s" "Checking $SERVICE_NAME"
    if [ -f $PIDFILE ] && [ -s $PIDFILE ]; then
        PID=$(cat $PIDFILE)
            if [ -z "$(ps axf | grep ${PID} | grep -v grep)" ]; then
                printf "%s\n" "The process appears to be dead but pidfile still exists"
            else
                echo "Running, the PID is $PID"
            fi
    else
        printf "%s\n" "Service not running"
    fi
}

boot() {
    start
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  status)
    status
    ;;
  restart)
    stop
    start
    ;;
  *)
    echo "Usage: $0 {start|stop|status|restart}"
esac
