#!/bin/sh

PKG="syno-balance"
PKG_DIR="/var/packages/${PKG}/target"
DAEMON="${PKG_DIR}/bin/syno-daemon.sh"
DAEMON_PID="${PKG_DIR}/var/syno-balance.pid"

case "$1" in
  start)
    mkdir -p "${PKG_DIR}/var"
    if [ -f "$DAEMON_PID" ] && kill -0 "$(cat "$DAEMON_PID")" 2>/dev/null; then
      echo "Already running"
      exit 0
    fi
    setsid "$DAEMON" &
    echo $! > "$DAEMON_PID"
    echo "Started"
    ;;
  stop)
    if [ -f "$DAEMON_PID" ]; then
      kill "$(cat "$DAEMON_PID")" 2>/dev/null
      sleep 1
      kill -9 "$(cat "$DAEMON_PID")" 2>/dev/null
      rm -f "$DAEMON_PID"
    fi
    echo "Stopped"
    ;;
  status)
    [ -f "$DAEMON_PID" ] && kill -0 "$(cat "$DAEMON_PID")" 2>/dev/null && exit 0
    exit 1
    ;;
  *)
    echo "Usage: $0 {start|stop|status}"
    ;;
esac
