#!/bin/sh
#
# azstank-monitor Startup script for the AZS-side Tanker API monitoring
#
### BEGIN INIT INFO
# Provides: azstankmon
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6 
# Short-Description: Yandex.Tanker TRK Monitor
# Description: Yandex.Tanker TRK Monitor
### END INIT INFO

SCRIPTNAME=$(basename $0)

AZSMONTRK_APP="/opt/bukts-yandex/libexec/azsmontrk"
AZSMONTRK_CFG="/etc/opt/bukts-yandex/config-azs.js"
AZSMONTRK_ARGS="-c ${AZSMONTRK_CFG}"
APPNAME=$(basename $AZSMONTRK_APP)
AZSMONTRK_RUNPATH="/var/opt/bukts-yandex/run/"
AZSMONTRK_PID="${AZSMONTRK_RUNPATH}/${APPNAME}.pid"
AZSMONTRK_USER="www-data"
AZSMONTRK_GROUP="www-data"

DESC="Монитор Яндекс.Заправки"
ERR=0

# Gracefully exit if the package has been removed.
test -x ${AZSMONTRK_APP?} || exit 0

start() {
    ERR=0
    
    echo -n "Запуск сервиса \"$DESC\" :"
    
    if [ ! -f ${AZSMONTRK_CFG?} ]; then
        echo "Отсутствует файла с конфигурацией cервиса."
        exit 0
    fi

    PIDS=`ps ax | grep ${AZSMONTRK_APP?} | grep -v grep | awk '{print $1}'`
    if [ ! -z "${PIDS?}" ]; then
        echo " Сервис уже работает (pid=${PIDS?})"
        exit 0
    fi
    
    if [ -f "${AZSMONTRK_PID}" ] ; then
      rm -f "${AZSMONTRK_PID}" 2>/dev/null
    fi  

    sudo -u $AZSMONTRK_USER $AZSMONTRK_APP $AZSMONTRK_ARGS > /dev/null 2>&1

    ERR=$?
    if [ $ERR -ne 0 ]; then
        echo -n " ERROR"
    else
        if [ -f "${AZSMONTRK_PID}" ] ; then
            procnum=`cat ${AZSMONTRK_PID} 2>/dev/null`
        fi    
        echo -n " OK [${procnum?}]"
    fi
    echo "."
}

stop() {
    echo -n "Остановка сервиса \"$DESC\" :"
    
    PIDS=`ps ax | grep ${AZSMONTRK_APP?} | grep -v grep | awk '{print $1}'`
    if [ -z "${PIDS?}" ]; then
      echo -n "Нет работающего сервиса"
    else
      ERR=0
      for procnum in ${PIDS?}
      do
        kill ${procnum?}
        ERR=$?
        if [ $ERR -ne 0 ]; then
          echo -n " ERROR [${procnum?}]"
        else
          echo -n " OK [${procnum?}]"
          if [ -f "${AZSMONTRK_PID}" ] ; then
            rm -f "${AZSMONTRK_PID}" 2>/dev/null
          fi  
        fi
      done
    fi
    echo "."
    #kill -QUIT `cat $AZSMONTRK_PID` || echo -n "not running"
}
restart() {
    kill -HUP `cat $AZSMONTRK_PID` || echo -n "can not reload"
}
case "$1" in
start)
    start
;;
stop)
    stop
;;
restart|reload|force-reload)
    stop
    # One second might not be time enough for a daemon to stop,
    # if this happens, d_start will fail (and dpkg will break if
    # the package is being upgraded). Change the timeout if needed
    # be, or change d_stop to have start-stop-daemon use --retry.
    # Notice that using --retry slows down the shutdown process somewhat.
    sleep 1
    start
;;
*)
    echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
    exit 3
;;
esac

exit $?
