#!/bin/sh
### BEGIN INIT INFO
# Provides:          nginx-ui
# Required-Start:    $network $remote_fs $local_fs
# Required-Stop:     $network $remote_fs $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start or stop the Nginx UI
### END INIT INFO

NAME="nginx-ui"
DAEMON="/usr/bin/$NAME"
PIDFILE="/var/run/$NAME.pid"
CONFIG="/usr/local/etc/nginx-ui/app.ini"

[ -x "$DAEMON" ] || exit 0

start() {
    echo "Starting $NAME..."
    # BusyBox compatible syntax
    start-stop-daemon -S -b -p $PIDFILE -m -x $DAEMON -- $CONFIG
    echo "$NAME started"
}

stop() {
    echo "Stopping $NAME..."
    # BusyBox compatible syntax
    start-stop-daemon -K -p $PIDFILE -R 10
    rm -f $PIDFILE
    echo "$NAME stopped"
}

status() {
    if [ -f $PIDFILE ]; then
        PID=$(cat $PIDFILE)
        if kill -0 $PID > /dev/null 2>&1; then
            echo "$NAME is running (PID: $PID)"
            exit 0
        else
            echo "$NAME is not running (stale PID file)"
            exit 1
        fi
    else
        echo "$NAME is not running"
        exit 3
    fi
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    status)
        status
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac

exit 0
