#!/bin/sh
# ==========================================================================
#  S98retro-input -- Init script for Retro Game Launcher Input Mapper
#
#  Starts the uinput gamepad translator daemon that converts the H2's
#  rotary encoder + buttons into a standard Linux gamepad.
#
#  This runs BEFORE the retro module (S99broker launches h2_test
#  which can dispatch retro.mod).  The virtual gamepad must exist
#  before any emulator binary tries to open it.
# ==========================================================================
### BEGIN INIT INFO
# Provides:          S98retro-input
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: OreBolt OS retro gamepad mapper daemon
# Description:       Maps scroll-wheel + button events to virtual HID gamepad.
### END INIT INFO

DAEMON="/usr/bin/retro_input_mapper"
PIDFILE="/var/run/retro_input_mapper.pid"

case "$1" in
    start)
        if [ ! -x "$DAEMON" ]; then
            echo "retro-input: $DAEMON not found or not executable"
            exit 1
        fi
        if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
            echo "retro-input: already running (pid $(cat "$PIDFILE"))"
            exit 0
        fi
        echo "retro-input: starting gamepad mapper daemon..."
        "$DAEMON" &
        echo $! > "$PIDFILE"
        echo "retro-input: started (pid $!)"
        ;;
    stop)
        if [ -f "$PIDFILE" ]; then
            pid="$(cat "$PIDFILE")"
            if kill -0 "$pid" 2>/dev/null; then
                echo "retro-input: stopping (pid $pid)..."
                kill -TERM "$pid"
                # wait up to 2 seconds for clean exit
                i=0
                while kill -0 "$pid" 2>/dev/null && [ "$i" -lt 20 ]; do
                    usleep 100000
                    i=$((i + 1))
                done
                if kill -0 "$pid" 2>/dev/null; then
                    kill -KILL "$pid"
                fi
                echo "retro-input: stopped"
            else
                echo "retro-input: not running (stale pidfile)"
            fi
            rm -f "$PIDFILE"
        else
            echo "retro-input: not running"
        fi
        ;;
    restart)
        "$0" stop
        "$0" start
        ;;
    status)
        if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
            echo "retro-input: running (pid $(cat "$PIDFILE"))"
        else
            echo "retro-input: stopped"
            exit 1
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac

exit 0