#!/bin/sh
### BEGIN INIT INFO
# Provides:          zpdpsvc
# Required-Start:    $local_fs $network $time
# Required-Stop:     $local_fs $network $time
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Description:       APM Insight PHP agent
### END INIT INFO

PATH=/bin:/usr/bin:/sbin:/usr/sbin:/opt/zpa/bin
NAME=zpdpsvc
PIDNAME=zpdp
SCRIPT=/etc/init.d/"$NAME"
#RUNAS=<USERNAME>

PIDFILE=/opt/zpa/bin/pid
LOGFILE=/opt/zpa/logs/installer.log

start() {
  case "$(pidof zpdp | wc -w)" in
    0) echo "Starting service..."
        ;;
    *) echo "Service is running. To stop enter service zpdpsvc stop"
        return 0
        ;;
  esac
  #local CMD="$SCRIPT &> \"$LOGFILE\" & echo \$!"
  #su -c "$CMD" $RUNAS > "$PIDFILE"
  cd /opt/zpa/bin
  export LD_LIBRARY_PATH=../lib/
    ./zpdp -loglevel WARNING & > "$PIDFILE"
	if [ "$?" = "0" ] ; then
		echo "Agent started"
	else
		echo "Error starting the process"
	fi
	cd - > /dev/null 2>&1
  echo 'Service started' 
}

stop() {
  case "$(pidof zpdp | wc -w)" in
     0) echo "Service is stopped. To start enter service zpdpsvc start"
        return 0
        ;;
    *) echo "Stopping service..."
        ;;
  esac
  
  cd /opt/zpa/bin
  export LD_LIBRARY_PATH=../lib/
	./zpdp -loglevel WARNING -shutdown
	sleep 2
	echo "Agent stopped"
	kill -15 $(pidof zpdp) > /dev/null 2>&1
	rm -f "$PIDFILE" > /dev/null 2>&1
	cd - > /dev/null 2>&1
  echo 'Service stopped'
}

uninstall() {
  echo -n "Are you really sure you want to uninstall this service? That cannot be undone. [yes|No] "
  local SURE
  read SURE
  if [ "$SURE" = "yes" ]; then
    stop
    rm -f "$PIDFILE"
    echo "Notice: log file is not be removed: '$LOGFILE'" 
    update-rc.d -f $NAME remove
    rm -fv "$0"
  fi
}

servicestatus(){
 case "$(pidof zpdp | wc -w)" in
 0) echo "Service is stopped. To start enter service zpdpsvc start"
    ;;
 *) echo "Service is running. To stop enter service zpdpsvc stop"
    ;;
 esac
}

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