#!/usr/bin/env bash
# rootcmd — sudo allowlist wrapper (feature T1)
# deny-by-default: only allowlisted commands pass through to sudo.
#
# Usage:
#   rootcmd [--] CMD [ARGS...]      run `sudo CMD ARGS...` iff CMD is allowlisted
#   rootcmd --check CMD [ARGS...]   validate only (no exec); exit 0=allowed, 1=denied
#   rootcmd --list                  show the active allowlist (with source path)
#   rootcmd --init [--force]        write a default allowlist file (never overwrites)
#   rootcmd --help
#
# Allowlist file (one rule per line; # comments and blank lines ignored):
#   ${ROOTCMD_ALLOWFILE:-$HOME/.config/sysadmin_agent/rootcmd.allow}
#
# Rule forms:
#   cmd          allow any invocation of `cmd`
#   cmd sub      allow `cmd` only when its FIRST argument is `sub`
#   /abs/path    allow a specific absolute path (any args)
#
# No allowlist file => nothing is allowed (deny by default).
set -uo pipefail

ALLOWFILE="${ROOTCMD_ALLOWFILE:-$HOME/.config/sysadmin_agent/rootcmd.allow}"

usage() { awk 'NR>1 && /^#/{sub(/^# ?/,""); print} NR>1 && !/^#/ && NF{exit}' "$0"; }

require_allowfile() {
    if [ ! -f "$ALLOWFILE" ]; then
        echo "rootcmd: no allowlist at $ALLOWFILE" >&2
        echo "  run: $0 --init   (writes a conservative default you can edit)" >&2
        echo "  or set ROOTCMD_ALLOWFILE to point at your own allowlist." >&2
        exit 2
    fi
}

# is_allowed CMD [ARG...] — reads rules from $ALLOWFILE
is_allowed() {
    local cmd="$1" sub base t1 t2 rule
    base=$(basename "$cmd")
    sub="${2:-}"
    while IFS= read -r rule; do
        rule="${rule%%#*}"                       # strip comments
        rule=$(printf '%s' "$rule" | tr -s '[:space:]' ' ')  # collapse whitespace
        rule="${rule#"${rule%%[![:space:]]*}"}"  # ltrim
        rule="${rule%"${rule##*[![:space:]]}"}"  # rtrim
        [ -z "$rule" ] && continue
        t1="${rule%% *}"
        t2="${rule#* }"
        [ "$t2" = "$rule" ] && t2=""
        if [ "${t1:0:1}" = "/" ]; then
            [ "$cmd" = "$t1" ] || continue        # absolute-path rule
        else
            [ "$base" = "$t1" ] || continue       # command-name rule
        fi
        # name/path matched; enforce sub-command constraint if one is given
        if [ -z "$t2" ] || [ "$sub" = "$t2" ]; then
            return 0
        fi
    done < "$ALLOWFILE"
    return 1
}

init_default() {
    local force=0
    [ "${1:-}" = "--force" ] && force=1
    if [ -f "$ALLOWFILE" ] && [ "$force" -ne 1 ]; then
        echo "rootcmd: allowlist already exists at $ALLOWFILE (use --force to overwrite)" >&2
        exit 1
    fi
    mkdir -p "$(dirname "$ALLOWFILE")"
    cat > "$ALLOWFILE" <<'EOF'
# rootcmd allowlist — deny-by-default sudo guard (feature T1)
# Rule forms:
#   cmd          allow any invocation of `cmd`
#   cmd sub      allow `cmd` only when its FIRST argument is `sub`
#   /abs/path    allow a specific absolute path (any args)
# `#` comments and blank lines are ignored.
#
# This is a CONSERVATIVE default. Remove/restrict entries to your policy.
# NOTE: reboot/shutdown are deliberately NOT listed — add them explicitly if you
# ever want the agent to be able to reboot this host.
apt-get
apt
systemctl
journalctl
install
ufw
iptables
ip6tables
nft
nginx
certbot
rsync
timedatectl
EOF
    chmod 600 "$ALLOWFILE"
    echo "rootcmd: wrote default allowlist -> $ALLOWFILE"
}

list_rules() {
    require_allowfile
    echo "allowlist: $ALLOWFILE"
    echo "---"
    grep -vE '^\s*(#|$)' "$ALLOWFILE" || echo "(empty — nothing is allowed)"
}

case "${1:-}" in
    --init)        init_default "${2:-}"; exit 0 ;;
    --list)        list_rules; exit 0 ;;
    --help|-h)     usage; exit 0 ;;
    --check)       shift
                   require_allowfile
                   [ $# -ge 1 ] || { usage; exit 2; }
                   if is_allowed "$@"; then echo "ALLOWED: $*"; exit 0; else echo "DENIED: $*"; exit 1; fi ;;
    *)             [ $# -ge 1 ] || { usage; exit 2; }
                   [ "${1:-}" = "--" ] && shift
                   require_allowfile
                   if ! is_allowed "$@"; then
                       echo "rootcmd: DENIED (not in allowlist): $*" >&2
                       echo "  allowlist: $ALLOWFILE" >&2
                       echo "  inspect/edit with: $0 --list" >&2
                       exit 1
                   fi
                   exec sudo "$@" ;;
esac
