#!/bin/bash
### BEGIN INIT INFO
# Provides:          nx1led
# Required-Start:    $remote_fs loadcpufreq
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# X-Start-Before:    hddbootflush
# Short-Description: nx1 boot sequence
# Description:       Provides the ability to boot up automatically depending on available
#                    boot devices and ability to override boot using the boot menu.
### END INIT INFO
# VERSION: 4.0.0.29987

run_watchdog() {
    while true
    do
        start
        sleep 20
    done
}

stop() {
    SERVICE_PID="`ps -eO command | grep nx1button | grep python | grep -v grep | awk {'print $1'}`"
    WATCHDOG_PID="`ps -eO command | grep run_watchdog | grep -v grep |  awk {'print $1'}`"
    if [ "$SERVICE_PID" ]; then
        echo "Stopping Button Service... PID: " $SERVICE_PID
        kill -9 $SERVICE_PID
    fi
    if [ "$WATCHDOG_PID" ]; then
        echo "Stopping Button Service Watchdog... PID: " $WATCHDOG_PID
        kill -9 $WATCHDOG_PID
    fi
}

start() {
    SERVICE_PID="`ps -eO command | grep nx1button | grep python | grep -v grep | awk {'print $1'}`"
    if [ ! -z "$SERVICE_PID" ]; then
       echo "Button Service is already running with pid $SERVICE_PID"
       return 0
    fi
    echo "Starting Button Service..."
    nohup python /root/tools/gpio/led/nx1button.py 2>&1&

    if [[ $(ps -eO command | grep nx1button| grep -v grep | awk {'print $1'}) ]]; then
        echo "OK"
    fi
}

start_watchdog() {
    WATCHDOG_PID="`ps -eO command | grep run_watchdog | grep button | grep -v grep |  awk {'print $1'}`"
    if [ "$WATCHDOG_PID" ]; then
        echo "nx1button watchdog is already running with pid $WATCHDOG_PID"
        return 0
    fi
    bash -c "/etc/init.d/nx1button run_watchdog" 2>/dev/null 1>&2&
    echo "nx1button watchdog has been started"
}

case "$1" in
    start)
        start
        start_watchdog
        ;;
    restart|reload|force-reload)
        echo "Error: argument '$1' not supported" >&2
        exit 3
        ;;
  run_watchdog)
      run_watchdog
      ;;
  stop)
      stop
      ;;
  *)
      echo "Usage: nx1boot [start]" >&2
      exit 3
      ;;
esac
