#!/bin/bash

# Uncomment to debug
# set -x

PIDFILE=afi-adc64-system.pid
LOGFILE=afi-adc64-system.log
COMMAND="afi-adc64-system"
ARGS="--cli_mode --event_number 10000000 --data_dir /home/pmtlab/trash2"

usage() {
  echo "Usage: $0 { start | stop | status }"
  exit 1
}

start() {
  if [ -f $PIDFILE ]; then
    echo "The process seems running. $PIDFILE exists. PID: $(cat $PIDFILE)"
    exit 1
  else
    touch $PIDFILE
    if nohup $COMMAND $ARGS >> $LOGFILE 2>&1 & 
    then
      echo $! > $PIDFILE
      echo "$(date '+%Y-%m-%d %H:%M:%S'): START" >> $LOGFILE
    else
      echo "Error... "
      rm $PIDFILE
    fi
  fi
}

status() {
  if [ -f $PIDFILE ]; then
    echo "The process seems running. PID file exists: $PIDFILE PID: $(cat $PIDFILE)"
    ps -ef | grep -v grep | grep $(cat $PIDFILE)
  else
    echo "The process seems not running. There is no PID file"
  fi
}

ensure_stop() {
  BEGIN=$(date +%s)
  GRACE_TIMEOUT=10
  while true; do
    PID=`ps -ef | grep $COMMAND | grep -v grep | grep -v $0 | awk '{print $2}'`
    if [[ "$PID" && $(($(date +%s) - $BEGIN)) -gt $GRACE_TIMEOUT ]]; then
      echo "Could not stop gracefully. Trying to kill."
      echo $PID | xargs kill -SIGKILL
      if [ -f $PIDFILE ]; then
        rm $PIDFILE
      fi
      break
    fi

    if [[ "$PID" ]]; then
      sleep 1
    else
      break
    fi
  done
}

stop() {
  if [ -f $PIDFILE ]; then
    if kill $(cat $PIDFILE); then
      echo "$(date '+%Y-%m-%d %X'): STOP" >> $LOGFILE
    fi
    rm $PIDFILE
    ensure_stop
  else
    echo "No pid file. Already stopped?"
    exit 1
  fi
}

case "$1" in
  'start')
    start
    ;;
  'stop')
    stop
    ;;
  'status')
    status
    ;;
  *)
    usage
    ;;
esac

exit 0
