#!/bin/bash
#(@)ot-recorder
# Start on runlevels 3, 4 and 5. Start late, stop early.
# chkconfig: 345 95 05

# absolute path to executable binary
exec='/usr/sbin/ot-recorder'

# Program name
prog=$(basename $exec)

# Source config
if [ -f /etc/default/$prog ] ; then
    . /etc/default/$prog
fi


# PID file
pidfile="/var/run/${prog}.pid"

# Ensure full path to executable binary is found
! [ -x $exec ] && echo "$exec: executable not found" && exit 1

eval_cmd() {
  local rc=$1
  if [ $rc -eq 0 ]; then
    echo '[  OK  ]'
  else
    echo '[FAILED]'
  fi
  return $rc
}

start() {
  # see if running
  local pids=$(pgrep -f $exec)

  if [ -n "$pids" ]; then
    echo "$prog (pid $pids) is already running"
    return 0
  fi
  printf "%-50s%s" "Starting $prog: " ''
  umask 0002
  $exec $OTR_OPTS $OTR_TOPICS &

  # save pid to file if you want
  echo $! > $pidfile

  # check again if running
  pgrep -f $exec >/dev/null 2>&1
  eval_cmd $?
}

stop() {
  # see if running
  local pids=$(pgrep -f $exec)

  if [ -z "$pids" ]; then
    echo "$prog not running"
    return 0
  fi
  printf "%-50s%s" "Stopping $prog: " ''
  rm -f $pidfile
  kill -9 $pids
  eval_cmd $?
}

status() {
  # see if running
  local pids=$(pgrep -f $exec)

  if [ -n "$pids" ]; then
    echo "$prog (pid $pids) is running"
  else
    echo "$prog is stopped"
  fi
}

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

exit $?
