#!/bin/bash
# Privileged helper for Lite System Monitor.
# Invoked via pkexec; the polkit action com.linuxliteos.lite-system-monitor
# pins this path so polkit shows Lite System Monitor branding (icon + vendor)
# in the auth dialog instead of the generic "polkit project" prompt.
#
# Usage:
#   lite-system-monitor-helper service <action> <unit>
#       <action>: start|stop|restart|reload|enable|disable|mask|unmask
#   lite-system-monitor-helper kill <signal> <pid>
#       <signal>: 9 (KILL) | 15 (TERM) | 18 (CONT) | 19 (STOP)
#   lite-system-monitor-helper renice <nice> <pid>
#       <nice>: integer in -20..19
#
# Argument validation rejects anything that isn't a plain identifier / integer
# so this helper can't be tricked into running arbitrary commands.

set -e
export PATH="/usr/sbin:/usr/bin:/sbin:/bin"

_die() { echo "$*" >&2; exit 2; }

_safe_unit() {
    case "$1" in
        ''|*..*|*/*|*' '*) _die "Invalid unit name: $1" ;;
        *[!A-Za-z0-9._@:-]*) _die "Invalid characters in unit name: $1" ;;
    esac
}

_pos_int() {
    case "$1" in
        ''|*[!0-9]*) _die "Not a positive integer: $1" ;;
    esac
    [ "$1" -gt 0 ] || _die "Must be > 0: $1"
}

_signed_int() {
    case "$1" in
        -[0-9]*|[0-9]*) ;;
        *) _die "Not an integer: $1" ;;
    esac
}

case "$1" in
    service)
        action="$2"
        unit="$3"
        case "$action" in
            start|stop|restart|reload|enable|disable|mask|unmask) ;;
            *) _die "Unknown service action: $action" ;;
        esac
        _safe_unit "$unit"
        exec systemctl "$action" "$unit"
        ;;
    kill)
        sig="$2"
        pid="$3"
        case "$sig" in 9|15|18|19) ;; *) _die "Unsupported signal: $sig" ;; esac
        _pos_int "$pid"
        exec kill "-$sig" "$pid"
        ;;
    renice)
        nice="$2"
        pid="$3"
        _signed_int "$nice"
        [ "$nice" -ge -20 ] && [ "$nice" -le 19 ] || _die "nice out of range -20..19: $nice"
        _pos_int "$pid"
        exec renice -n "$nice" -p "$pid"
        ;;
    *)
        _die "Unknown action: $1"
        ;;
esac
