#!/bin/sh

PKG="kit-connect"
PKG_DIR="/var/packages/${PKG}/target"
DAEMON="${PKG_DIR}/bin/connect-daemon.sh"
DAEMON_PID="${PKG_DIR}/var/daemon.pid"
DASHBOARD="${PKG_DIR}/bin/serve-dashboard.sh"
DASHBOARD_PID="${PKG_DIR}/var/dashboard.pid"

case "$1" in
  start)
    mkdir -p "${PKG_DIR}/var"

    # Start main daemon
    if [ -f "$DAEMON_PID" ] && kill -0 "$(cat "$DAEMON_PID")" 2>/dev/null; then
      echo "Daemon already running"
    else
      setsid "$DAEMON" &
      echo $! > "$DAEMON_PID"
      echo "Daemon started"
    fi

    # Start dashboard server (port 8089)
    if [ -x "$DASHBOARD" ] && command -v busybox >/dev/null 2>&1; then
      if [ -f "$DASHBOARD_PID" ] && kill -0 "$(cat "$DASHBOARD_PID")" 2>/dev/null; then
        echo "Dashboard already running"
      else
        "$DASHBOARD" 8089 &
        echo $! > "$DASHBOARD_PID"
        echo "Dashboard started on port 8089"
      fi
    fi
    ;;
  stop)
    # Stop dashboard
    if [ -f "$DASHBOARD_PID" ]; then
      kill "$(cat "$DASHBOARD_PID")" 2>/dev/null
      sleep 1
      kill -9 "$(cat "$DASHBOARD_PID")" 2>/dev/null
      rm -f "$DASHBOARD_PID"
      echo "Dashboard stopped"
    fi

    # Stop daemon
    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"
      echo "Daemon stopped"
    fi
    ;;
  status)
    if [ -f "$DAEMON_PID" ] && kill -0 "$(cat "$DAEMON_PID")" 2>/dev/null; then
      echo "Daemon: running (PID $(cat "$DAEMON_PID"))"
    else
      echo "Daemon: stopped"
    fi
    if [ -f "$DASHBOARD_PID" ] && kill -0 "$(cat "$DASHBOARD_PID")" 2>/dev/null; then
      echo "Dashboard: running on port 8089 (PID $(cat "$DASHBOARD_PID"))"
      exit 0
    else
      echo "Dashboard: stopped"
    fi
    [ -f "$DAEMON_PID" ] && kill -0 "$(cat "$DAEMON_PID")" 2>/dev/null && exit 0
    exit 1
    ;;
  *)
    echo "Usage: $0 {start|stop|status}"
    ;;
esac
