#!/bin/sh
# /etc/init.d/hermes-node-agent
# SysVinit script for Hermes Node Agent
#
# chkconfig: 2345 95 05
# description: Hermes Node Agent — reverse-connected WebSocket client

### BEGIN INIT INFO
# Provides:          hermes-node-agent
# Required-Start:    $network $remote_fs $syslog
# Required-Stop:     $network $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Hermes Node Agent
# Description:       Reverse-connected WebSocket node agent.
### END INIT INFO

NAME="hermes-node-agent"
DAEMON="/usr/bin/python3"
SCRIPT_DIR="/usr/local/bin"
DAEMON_SCRIPT="${SCRIPT_DIR}/hermes_node_agent.py"
PIDFILE="/var/run/${NAME}.pid"
LOGFILE="/var/log/${NAME}.log"
USER="root"
GROUP="root"

# Check daemon exists
if [ ! -x "$DAEMON" ]; then
    echo "$DAEMON not found or not executable."
    exit 5
fi

if [ ! -f "$DAEMON_SCRIPT" ]; then
    echo "$DAEMON_SCRIPT not found."
    exit 5
fi

# Ensure config exists
if [ ! -f "/etc/hermes-node/config.json" ]; then
    echo "/etc/hermes-node/config.json not found."
    exit 6
fi

. /lib/lsb/init-functions 2>/dev/null || true

start() {
    echo "Starting $NAME..."
    if [ -f "$PIDFILE" ]; then
        PID=$(cat "$PIDFILE")
        if kill -0 "$PID" 2>/dev/null; then
            echo "$NAME is already running (PID $PID)."
            return 0
        else
            rm -f "$PIDFILE"
        fi
    fi
    touch "$LOGFILE"
    chown "$USER:$GROUP" "$LOGFILE" 2>/dev/null || chmod 644 "$LOGFILE"
    $DAEMON $DAEMON_SCRIPT >> "$LOGFILE" 2>&1 &
    echo $! > "$PIDFILE"
    sleep 1
    if kill -0 $(cat "$PIDFILE") 2>/dev/null; then
        echo "$NAME started (PID $(cat $PIDFILE))."
    else
        echo "$NAME failed to start. Check $LOGFILE"
        exit 1
    fi
}

stop() {
    echo "Stopping $NAME..."
    if [ -f "$PIDFILE" ]; then
        PID=$(cat "$PIDFILE")
        if kill -0 "$PID" 2>/dev/null; then
            kill "$PID" 2>/dev/null
            for i in $(seq 1 30); do
                if ! kill -0 "$PID" 2>/dev/null; then
                    break
                fi
                sleep 0.5
            done
            if kill -0 "$PID" 2>/dev/null; then
                echo "Force killing..."
                kill -9 "$PID" 2>/dev/null
                sleep 1
            fi
        fi
        rm -f "$PIDFILE"
        echo "$NAME stopped."
    else
        echo "$NAME is not running."
    fi
    pkill -f "hermes_node_agent.py" 2>/dev/null || true
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        sleep 1
        start
        ;;
    reload|force-reload)
        echo "Reload not supported, restarting..."
        stop
        sleep 1
        start
        ;;
    status)
        RUNNING=0
        if [ -f "$PIDFILE" ]; then
            PID=$(cat "$PIDFILE")
            if kill -0 "$PID" 2>/dev/null; then
                echo "$NAME is running (PID $PID)."
                RUNNING=1
            else
                echo "$NAME is not running (stale PID file)."
                RUNNING=0
            fi
        else
            PID=$(pgrep -f "hermes_node_agent.py" | head -1)
            if [ -n "$PID" ]; then
                echo "$NAME is running (PID $PID) but no PID file."
                RUNNING=1
            else
                echo "$NAME is not running."
                RUNNING=0
            fi
        fi
        exit $(( 1 - RUNNING ))
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac

exit 0
