#!/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 resolution:
#   * when running as root, a ROOT-OWNED system allowfile wins. The per-user
#     copy lives in the agent's own $HOME, so it is writable by the agent and
#     therefore cannot be the boundary — only /etc/sysadmin-agent/ can be.
#   * otherwise: ROOTCMD_ALLOWFILE, then the per-user default.
SYSTEM_ALLOWFILE="/etc/sysadmin-agent/rootcmd.allow"
ALLOWFILE="${ROOTCMD_ALLOWFILE:-$HOME/.config/sysadmin_agent/rootcmd.allow}"
if [ "$(id -u)" -eq 0 ] && [ -f "$SYSTEM_ALLOWFILE" ]; then
    ALLOWFILE="$SYSTEM_ALLOWFILE"
fi

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
    # Root-side integrity guard: an allowfile that a non-root user can modify is
    # not a boundary, it is a suggestion. Refuse rather than silently trust it.
    if [ "$(id -u)" -eq 0 ]; then
        local owner mode
        owner=$(stat -c '%u' "$ALLOWFILE" 2>/dev/null || echo x)
        mode=$(stat -c '%a' "$ALLOWFILE" 2>/dev/null || echo 777)
        if [ "$owner" != 0 ] || [ $(( 0$mode & 022 )) -ne 0 ]; then
            echo "rootcmd: REFUSING insecure allowfile $ALLOWFILE" >&2
            echo "  (owner uid=$owner mode=$mode — must be root-owned, not group/other writable)" >&2
            echo "  fix: sudo install -o root -g root -m 0644 $ALLOWFILE $ALLOWFILE" >&2
            exit 3
        fi
    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
