#!/bin/bash

### BEGIN INIT INFO
# Provides:          fing-kit
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Fing Kit
### END INIT INFO

# Copyright 2019 by Fing LTD

CMD="/usr/local/lib/fing/fing.bin"
DAEMON="fing-kit"
OPTIONS="--silent --kit /etc/fing/kit.properties"
LD_LIBRARY_PATH="/usr/local/lib/fing"

# Start the service
start()
{
  if pidof ${CMD} > /dev/null; then
    echo "Only one instance allowed."
    exit 1
  fi

  echo -n "Starting fing-kit: "

  export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}

  ulimit -n 1024
  ulimit -c 0

  nohup ${CMD} ${OPTIONS} >/dev/null 2>/dev/null &

  if [ $? -eq 0 ]; then
    echo "started"
    exit 0
  else
    echo "failed"
    exit 1
  fi

}

# Stop the service
stop()
{
  if ! pidof ${CMD} > /dev/null; then
    echo "Not running."
    exit 1
  fi

  echo -n "Stopping fing-kit: "

  if kill -9 $(pidof ${CMD}) >/dev/null 2> /dev/null; then
    echo "stopped"
    exit 0
  else
    echo "failed"
    exit 1
  fi

}

# Status of the service
status()
{
  if pidof ${CMD}; then
    echo "${DAEMON} is running"
    exit 0
  else
    echo "${DAEMON} is not running"
    exit 1
  fi
}

# Main Logic
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  status)
        status
        ;;
  restart|reload|condrestart)
        stop
        sleep 3
        start
        ;;
  *)
        echo $"Usage: $0 {start|stop|restart|reload|status}"
        exit 1
esac
exit 0
