#!/bin/sh

START=50
STOP=50

SERVICE_NAME="subrose"
SERVICE_FILE="/opt/etc/init.d/S50subrose"
LOG_FILE="/opt/var/log/$SERVICE_NAME.log"

SUP_PID_FILE="/opt/var/run/subrose-sup.pid"

# @feature:dv-supervisor
start_service() {
    echo "Starting $SERVICE_NAME..."
    if pgrep -x "$SERVICE_NAME" > /dev/null 2>&1; then
        echo "$SERVICE_NAME is already running"
        exit 1
    fi
    mkdir -p /opt/var/run
    # Entware init.d has no native respawn — run a supervisor loop that restarts
    # the agent on crash OR self-exit (the agent self-exits on sustained
    # node-unreachability to force a fresh CoAPS handshake).
    # For mainnet change --env testnet to --env mainnet below.
    ( cd /opt/subrose
      while :; do
        ./"$SERVICE_NAME" --env testnet >> "$LOG_FILE" 2>&1
        echo "$(date): $SERVICE_NAME exited ($?) — respawning in 5s" >> "$LOG_FILE"
        sleep 5
      done ) &
    echo $! > "$SUP_PID_FILE"
    echo "Service $SERVICE_NAME started (supervised)"
}

stop_service() {
    echo "Stopping $SERVICE_NAME..."
    # kill the supervisor first so it doesn't respawn the agent we're stopping
    [ -f "$SUP_PID_FILE" ] && kill "$(cat "$SUP_PID_FILE")" 2>/dev/null
    rm -f "$SUP_PID_FILE"
    killall "$SERVICE_NAME" 2>/dev/null || true
    echo "Service $SERVICE_NAME stopped"
}

restart_service() { stop_service; start_service; }

status_service() {
    if pgrep -x "$SERVICE_NAME" > /dev/null 2>&1; then
        echo "Service $SERVICE_NAME is running"
    else
        echo "Service $SERVICE_NAME is not running"
    fi
}

enable_service() {
    ln -sf "$SERVICE_FILE" "/etc/rc.d/S${START}${SERVICE_NAME}"
    ln -sf "$SERVICE_FILE" "/etc/rc.d/K${STOP}${SERVICE_NAME}"
    echo "$SERVICE_NAME enabled"
}

disable_service() {
    rm -f "/etc/rc.d/S${START}${SERVICE_NAME}" "/etc/rc.d/K${STOP}${SERVICE_NAME}"
    echo "$SERVICE_NAME disabled"
}

case "$1" in
    start)   start_service   ;;
    stop)    stop_service    ;;
    restart) restart_service ;;
    status)  status_service  ;;
    enable)  enable_service  ;;
    disable) disable_service ;;
    *)
        echo "Usage: $0 {start|stop|restart|status|enable|disable}"
        exit 1
        ;;
esac
exit 0
