#!/bin/sh
# rc.ckb-next
# Start/stop the ckb-next daemon on Slackware

NAME="ckb-next-daemon"
DESC="Corsair keyboards and mice"
PIDFILE="/dev/input/ckb0/pid"     # Do not change
DAEMON="/usr/bin/ckb-next-daemon"

# Only start if installed
if [ ! -x "$DAEMON" ]; then
    echo "$DAEMON not installed."
    exit 1
fi

start() {
    echo "Starting $DESC ($NAME)"
    if [ -f "$PIDFILE" ]; then
        echo "$NAME already running (pid file exists)."
        return 0
    fi
    # Launch in background
    $DAEMON >> /var/log/ckb-next-daemon.log 2>&1 &
    sleep 1
    if [ ! -f "$PIDFILE" ]; then
        echo "Failed to start $NAME."
    fi
}

stop() {
    echo "Stopping $DESC ($NAME)..."
    if [ -f "$PIDFILE" ]; then
        kill "$(cat $PIDFILE)" 2>/dev/null
        rm -f "$PIDFILE"
        echo "$NAME stopped."
    else
        echo "$NAME not running."
    fi
}

restart() {
    stop
    sleep 1
    start
}

status() {
    if [ -f "$PIDFILE" ]; then
        PID=$(cat "$PIDFILE")
        if ps -p "$PID" >/dev/null 2>&1; then
            echo "$NAME is running (PID $PID)"
            return 0
        else
            echo "PID file exists but process does not."
            return 1
        fi
    else
        echo "$NAME is not running."
        return 3
    fi
}

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

exit 0
