#!/usr/bin/env bash
# fw — ufw firewall wrapper (feature T13)
# Named ufw wrapper with safe defaults.
#
# Usage:
#   fw status [verbose|numbered]
#   fw allow PORT[/PROTO]|APP [--from IP|anywhere] [--comment TEXT] [--both]
#   fw deny  PORT[/PROTO]|APP [--from IP|anywhere] [--comment TEXT] [--both]
#   fw delete NUM|RULE
#   fw enable [--force]
#   fw disable
#   fw default allow|deny|reject incoming|outgoing|routed
#   fw app list
#   fw --help
#
# Safe defaults:
#   - `allow`/`deny` default to proto tcp (pass --both for tcp+udp).
#   - `default allow incoming` is refused (too dangerous) — keep default deny.
#   - `enable` refuses to turn the firewall on if no SSH (22) rule is visible
#     and you're not passing --force, to avoid locking yourself out.
set -uo pipefail

ufw_bin="${UFW:-$(command -v ufw 2>/dev/null || echo ufw)}"

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

ufw_run() {
    if [ "$(id -u)" -eq 0 ]; then
        "$ufw_bin" "$@"
    elif command -v sudo >/dev/null 2>&1; then
        sudo "$ufw_bin" "$@"
    else
        "$ufw_bin" "$@"
    fi
}

is_port_spec() { grep -qE '^[0-9]+(/.*)?$' <<<"$1"; }

rule_for() {
    case "$1" in
        */*) echo "$1" ;;
        *)   echo "$1/tcp" ;;
    esac
}

allow_deny() {
    local verb="$1"; shift
    local spec="" from="" comment="" both=0
    while [ $# -gt 0 ]; do
        case "$1" in
            --from)    from="$2"; shift 2 ;;
            --comment) comment="$2"; shift 2 ;;
            --both)    both=1; shift ;;
            --help|-h) usage; exit 0 ;;
            -*) echo "fw: unknown option: $1" >&2; usage; exit 2 ;;
            *) spec="$1"; shift ;;
        esac
    done
    [ -n "$spec" ] || { echo "fw: PORT[/PROTO] or APP is required" >&2; usage; exit 2; }
    local args=( "$verb" )
    if is_port_spec "$spec" && [ "$both" -ne 1 ]; then
        args+=( "$(rule_for "$spec")" )
    else
        args+=( "$spec" )
    fi
    [ -n "$from" ] && args+=( from "$from" )
    [ -n "$comment" ] && args+=( comment "$comment" )
    ufw_run "${args[@]}"
}

status_cmd() {
    case "${1:-}" in
        verbose)  ufw_run status verbose ;;
        numbered) ufw_run status numbered ;;
        *)        ufw_run status ;;
    esac
}

ssh_allowed() {
    local out
    out="$(ufw_run status 2>/dev/null || true)"
    if echo "$out" | grep -qi 'Status: inactive'; then
        # Pending rules are not shown while inactive — be conservative.
        return 1
    fi
    echo "$out" | grep -qiE '(^|[[:space:]])22(/[[:alnum:]]+)?([[:space:]]|$)|openssh|ssh(/|\b)' && return 0
    return 1
}

enable_cmd() {
    local force=0
    [ "${1:-}" = "--force" ] && force=1
    if [ "$force" -ne 1 ] && ! ssh_allowed; then
        echo "fw: refusing to enable — no SSH (22) allow rule is visible." >&2
        echo "    Enabling with default-incoming-deny could lock you out." >&2
        echo "    Add an allow rule first (e.g. 'fw allow 22 --comment ssh')," >&2
        echo "    or pass --force if you are on a local console and accept the risk." >&2
        exit 1
    fi
    ufw_run enable
}

default_cmd() {
    local policy="${1:-}" dir="${2:-}"
    case "$policy" in allow|deny|reject) ;; *) echo "fw: policy must be allow|deny|reject" >&2; usage; exit 2 ;; esac
    case "$dir" in incoming|outgoing|routed) ;; *) echo "fw: direction must be incoming|outgoing|routed" >&2; usage; exit 2 ;; esac
    if [ "$policy" = allow ] && [ "$dir" = incoming ]; then
        echo "fw: refusing 'default allow incoming' — too dangerous." >&2
        echo "    Keep default deny on incoming; open only the ports you need." >&2
        exit 1
    fi
    ufw_run default "$policy" "$dir"
}

case "${1:-}" in
    status)  shift; status_cmd "$@" ;;
    allow)   shift; allow_deny allow "$@" ;;
    deny)    shift; allow_deny deny "$@" ;;
    delete)  shift; ufw_run delete "${1:-}" ;;
    enable)  shift; enable_cmd "$@" ;;
    disable) ufw_run disable ;;
    default) shift; default_cmd "$@" ;;
    app)     shift; ufw_run app "$@" ;;
    --help|-h) usage ;;
    *) usage; exit 2 ;;
esac
