#!/bin/bash
set -euo pipefail

# Unit enablement records the saved operational choice. Explicit arguments are
# used by the service transaction; auto/boot restores choices before startup.
mode=${1:-auto}
proxy=${2:-boot}
boot_guard=0
[[ $mode != auto || $proxy != boot ]] || boot_guard=1
maintenance=0
[[ $mode != auto || $proxy != active ]] || maintenance=1
rules_dir=${HARRESI_IPTABLES_DIR:-/etc/iptables}
lists=${HARRESI_FIREWALL_LIST_HELPER:-/etc/harresi/firewall-rules}
runtime_intent=${HARRESI_RUNTIME_INTENT_FILE:-/run/harresi-services-runtime}
rules_recovery=${HARRESI_RULES_RECOVERY_FLAG:-/run/harresi-rules-recovery-required}
if ((maintenance)) && [[ -f $runtime_intent ]]; then
    # A maintenance save follows the current selection, including deliberately
    # stopped engines and a proxy awaiting recovery, without changing boot flags.
    read -r mode proxy < "$runtime_intent"
    case $mode:$proxy in
        IDS:on|IDS:off|IDPS:on|IDPS:off|stopped:on|stopped:off) ;;
        *) echo 'ERROR: intención de ejecución no válida; no se modifica el cortafuegos.' >&2; exit 1 ;;
    esac
elif [[ $mode == auto ]]; then
    ids=0; idps=0
    systemctl is-enabled --quiet suricata_ids.service && ids=1
    systemctl is-enabled --quiet suricata_idps.service && idps=1
    if ((ids && idps)); then
        echo 'ERROR: IDS e IDPS habilitados simultáneamente; no se modifica el cortafuegos.' >&2
        exit 1
    fi
    mode=stopped
    if ((idps)); then mode=IDPS; fi
    if ((ids)); then mode=IDS; fi
fi
case $mode in IDS|IDPS|stopped) ;; *) echo "Modo no válido: $mode" >&2; exit 1 ;; esac
case $proxy in
    boot) proxy=off; if systemctl is-enabled --quiet sslproxyd.service; then proxy=on; fi ;;
    active) proxy=off; if systemctl is-active --quiet sslproxyd.service; then proxy=on; fi ;;
    on|off) ;;
    *) echo 'Estado SSLproxy no válido.' >&2; exit 1 ;;
esac
work_dir=$(mktemp -d)
trap 'rm -rf "$work_dir"' EXIT
iptables-save > "$work_dir/previous"
preserve_gate=0
if ((maintenance)); then
    [[ ! -f $rules_recovery ]] || preserve_gate=1
    while IFS= read -r line; do
        case $line in *HARRESI_FAIL_CLOSED*|*harresi-suricata-fail-closed*) preserve_gate=1; break ;; esac
    done < "$work_dir/previous"
fi

# Strip only Harresi rules, including historical unlabelled queue/redirect
# rules. Keep the base NAT and administrator rules in the saved snapshot.
awk '
    /HARRESI_FAIL_CLOSED|harresi-suricata-fail-closed/ { next }
    /HARRESI IPT NFQUEUE |HARRESI IPT REDIRECT / { next }
    /^-A FORWARD / && / -i (eth0|eth1|wlan0|wlan1) / && / -o (eth0|eth1|wlan0|wlan1) / && / -j NFQUEUE / && / --queue-balance 0:1( |$)/ { next }
    /^-A PREROUTING / && / -p tcp / && / --dport 443 / && / -j REDIRECT / && / --to-ports 8443( |$)/ { next }
    { print }
' "$rules_dir/rules.v4" > "$work_dir/base"
: > "$work_dir/profile"
case $mode in
    IDS) cp "$rules_dir/iptables_ids" "$work_dir/profile" ;;
    IDPS)
        # HTTPS interception is supported only with the inline mode and proxy.
        awk -v proxy="$proxy" '
            /HARRESI IPT REDIRECT / || / -j REDIRECT / { if (proxy != "on") next }
            { print }
        ' "$rules_dir/iptables_idps" > "$work_dir/profile"
        if [[ -f $rules_dir/iptables_idps_wlan ]]; then
            wlan0=0; wlan1=0
            ip link show wlan0 >/dev/null 2>&1 && wlan0=1
            ip link show wlan1 >/dev/null 2>&1 && wlan1=1
            awk -v wlan0="$wlan0" -v wlan1="$wlan1" '
                /^-A / {
                    if ($0 ~ /(^| )-(i|o) wlan0( |$)/ && wlan0 != "1") next
                    if ($0 ~ /(^| )-(i|o) wlan1( |$)/ && wlan1 != "1") next
                }
                { print }
            ' "$rules_dir/iptables_idps_wlan" >> "$work_dir/profile"
        fi
        ;;
esac
if ((preserve_gate)) || { ((boot_guard)) && [[ $mode != stopped ]]; }; then
    # Keep boot and existing maintenance gates inside the first atomic filter
    # restore. Only the health-checked explicit service path may clear them.
    python3 - "$work_dir/base" <<'PY'
from pathlib import Path
import sys
path = Path(sys.argv[1])
lines = path.read_text().splitlines()
start = lines.index('*filter')
end = lines.index('COMMIT', start)
first = next((i for i in range(start+1, end) if lines[i].startswith('-A ')), end)
lines[first:first] = [
    ':HARRESI_FAIL_CLOSED - [0:0]',
    '-A FORWARD -m comment --comment "harresi-suricata-fail-closed" -j HARRESI_FAIL_CLOSED',
    '-A INPUT -p tcp --dport 8443 -m comment --comment "harresi-suricata-fail-closed" -j HARRESI_FAIL_CLOSED',
    '-A HARRESI_FAIL_CLOSED -j DROP',
]
path.write_text('\n'.join(lines)+'\n')
PY
fi
iptables-restore -w 5 --test < "$work_dir/base"
[[ ! -s $work_dir/profile ]] || iptables-restore -w 5 --test --noflush < "$work_dir/profile"
if [[ ${3:-} == validate ]]; then
    echo 'OK: perfiles de cortafuegos válidos; no se aplicaron.'
    exit 0
fi
restore_previous() {
    echo 'ERROR: aplicación fallida; restaurando el cortafuegos anterior.' >&2
    iptables-restore -w 5 < "$work_dir/previous" || echo 'CRÍTICO: recuperación del cortafuegos fallida.' >&2
    exit 1
}
iptables-restore -w 5 < "$work_dir/base" || restore_previous
if [[ -s $work_dir/profile ]]; then
    iptables-restore -w 5 --noflush < "$work_dir/profile" || restore_previous
fi
if [[ -x $lists ]]; then
    "$lists" restore || restore_previous
fi
printf '%s %s\n' "$mode" "$proxy" > "$work_dir/runtime"
install -m 0600 "$work_dir/runtime" "$runtime_intent.new" || restore_previous
mv -f "$runtime_intent.new" "$runtime_intent" || restore_previous
echo "Cortafuegos aplicado: modo=$mode; SSLproxy=$proxy (interceptación solo en IDPS)."
