#!/bin/sh
### BEGIN INIT INFO
# Provides:          collectd-web
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: collectd-web service
# Description:       Start/stop collectd-web
### END INIT INFO

DAEMON="python3 /usr/share/collectd-web/runserver.py"
NAME=collectd-web
PIDFILE=/var/run/$NAME.pid
LOGFILE=/var/log/$NAME.log
WORKDIR="/usr/share/collectd-web"

start() {
    echo "Starting $NAME..."
    if [ -f $PIDFILE ]; then
        echo "$NAME is already running!"
        exit 1
    fi
    cd $WORKDIR
    export PYTHONPATH="/usr/lib/python3/dist-packages:$PYTHONPATH"
    nohup $DAEMON > $LOGFILE 2>&1 &
    echo $! > $PIDFILE
    echo "$NAME started successfully."
}

stop() {
    echo "Stopping $NAME..."
    if [ ! -f $PIDFILE ]; then
        echo "$NAME is not running!"
        exit 1
    fi
    kill $(cat $PIDFILE) && rm -f $PIDFILE
    echo "$NAME stopped."
}

status() {
    if [ -f $PIDFILE ]; then
        echo "$NAME is running (PID: $(cat $PIDFILE))"
    else
        echo "$NAME is not running."
        exit 1
    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
