#!/usr/bin/bash
set -euo pipefail

export PATH=/usr/sbin:/usr/bin:/sbin:/bin
export DEBIAN_FRONTEND=noninteractive
export DEBIAN_PRIORITY=critical

APT=/usr/bin/apt-get

if (( EUID != 0 )); then
    echo "Must be run as root (via sudo)." >&2
    exit 1
fi

if (( $# < 1 )); then
    echo "Usage: agent-apt {update|install|remove} [packages...]" >&2
    exit 2
fi

action=$1
shift

validate_packages() {
    if (( $# == 0 )); then
        echo "At least one package is required." >&2
        exit 2
    fi

    if (( $# > 30 )); then
        echo "Maximum 30 packages per operation." >&2
        exit 2
    fi

    for pkg in "$@"; do
        # Only plain Debian package names.
        # No paths, versions, wildcards, options, or APT patterns.
        # install/remove also set APT::Cmd::Pattern-Only to prevent implicit
        # regex fallback for names containing dots or plus signs. Explicit
        # regex anchors (^ and $) are rejected by this validator.
        if [[ ! "$pkg" =~ ^[a-z0-9][a-z0-9.+-]*$ ]]; then
            echo "Invalid package name: $pkg" >&2
            exit 2
        fi
    done
}

case "$action" in
    update)
        if (( $# != 0 )); then
            echo "update takes no arguments." >&2
            exit 2
        fi
        exec "$APT" update
        ;;

    install)
        validate_packages "$@"
        exec "$APT" \
            -o APT::Cmd::Pattern-Only=true \
            --assume-yes \
            --no-install-recommends \
            --no-remove \
            install -- "$@"
        ;;

    remove)
        validate_packages "$@"

        # APT treats trailing + and - as operation modifiers.
        # Refuse ambiguous removal operands.
        for pkg in "$@"; do
            if [[ "$pkg" == *+ || "$pkg" == *- ]]; then
                echo "Ambiguous removal operand: $pkg" >&2
                exit 2
            fi
        done

        exec "$APT" \
            -o APT::Cmd::Pattern-Only=true \
            --assume-yes \
            remove -- "$@"
        ;;

    *)
        echo "Unknown operation: $action" >&2
        exit 2
        ;;
esac
