#!/usr/bin/env bash
# pkexec target for privileged AUR malware checks.
# Accepts exactly one flag; rejects everything else.
set -euo pipefail

MAIN_SCRIPT="/usr/lib/archcanary/archcanary.sh"

if [[ ! -x "$MAIN_SCRIPT" ]]; then
    echo "Error: main script not found at $MAIN_SCRIPT" >&2
    echo "Re-run: ./install.sh --system" >&2
    exit 1
fi

# pkexec resets HOME to /root, so dkms_allowlist.conf and other user config
# would never be found. Restore XDG_CONFIG_HOME from the invoking user's home.
if [[ -n "${PKEXEC_UID:-}" ]]; then
    _home=$(getent passwd "$PKEXEC_UID" | cut -d: -f6)
    if [[ -n "$_home" ]]; then
        export HOME="$_home"
        export XDG_CONFIG_HOME="$_home/.config"
        export XDG_CACHE_HOME="$_home/.cache"
    fi
fi

# --allowlist-add/--allowlist-remove are a distinct, single-flag path: they
# write to /etc/archcanary/*_allowlist.conf rather than run a scan, so they're
# validated and exec'd here directly instead of going through the ALLOWED_FLAGS
# scan-flag allowlist below. This script — not archcanary.sh — is the actual
# polkit-authorized privilege boundary (org.archcanary.policy authorizes this
# exec path with no argument restriction of its own), so NAME/VALUE are
# re-validated here even though archcanary.sh validates them again itself.
if [[ $# -eq 1 ]]; then
    case "$1" in
        --allowlist-add=*|--allowlist-remove=*)
            _spec="${1#*=}"
            if [[ "$_spec" != *:* ]]; then
                echo "Error: expected NAME:VALUE, got '$_spec'" >&2
                exit 1
            fi
            _name="${_spec%%:*}"
            _value="${_spec#*:}"
            case "$_name" in
                dkms|systemd|bpftool|autostart) ;;
                *)
                    echo "Error: invalid allowlist name '$_name'" >&2
                    exit 1
                    ;;
            esac
            # Kept identical to archcanary.sh's _allowlist_cli validation — see
            # its comment for why '/' is allowed (autostart full-path values)
            # and ':' is not (would corrupt the IFS=: multi-value join).
            if [[ ! "$_value" =~ ^[A-Za-z0-9/][A-Za-z0-9._@+/-]{0,127}$ ]]; then
                echo "Error: invalid allowlist value '$_value'" >&2
                exit 1
            fi
            unset _spec _name _value
            exec "$MAIN_SCRIPT" "$1"
            ;;
    esac
fi

ALLOWED_FLAGS=(--full --refresh --no-aur-audit --check-kmod --check-bpftool --check-ebpf --check-lynis --check-pkginteg --run-lynis --no-notify --no-summary --audit-rules-set --lynis-config-set)

for _arg in "$@"; do
    _ok=false
    for _f in "${ALLOWED_FLAGS[@]}"; do [[ "$_arg" == "$_f" ]] && _ok=true && break; done
    if ! $_ok; then
        echo "Error: invalid flag '$_arg'" >&2
        printf 'Allowed: %s\n' "${ALLOWED_FLAGS[*]}" >&2
        exit 1
    fi
done
unset _arg _ok _f

exec "$MAIN_SCRIPT" "$@" --no-notify
