#!/bin/bash
set -euo pipefail
umask 077
FIREWALL=${HARRESI_FIREWALL_HELPER:-/usr/local/sbin/harresi-apply-firewall}
SOCKET_DIR=${HARRESI_SOCKET_DIR:-/run}
LOCK=${HARRESI_SERVICE_LOCK:-/run/lock/harresi-services.lock}
RULES_RECOVERY=${HARRESI_RULES_RECOVERY_FLAG:-/run/harresi-rules-recovery-required}
PACKAGE_RECOVERY=${HARRESI_PACKAGE_RECOVERY_FLAG:-/run/harresi-package-recovery-required}
RUNTIME_INTENT=${HARRESI_RUNTIME_INTENT_FILE:-/run/harresi-services-runtime}
SURICATA_BIN=${HARRESI_SURICATA_BIN:-/usr/bin/suricata}
SURICATA_CONFIG_DIR=${HARRESI_SURICATA_CONFIG_DIR:-/etc/suricata}
UNITS=(suricata_ids suricata_idps suricata_mitm sslproxyd suricata-aggregator suricata-monitor)

saved_mode() {
    local ids=0 idps=0
    systemctl is-enabled --quiet suricata_ids && ids=1
    systemctl is-enabled --quiet suricata_idps && idps=1
    if ((ids && idps)); then echo 'ERROR: IDS e IDPS habilitados a la vez.' >&2; return 1; fi
    if ((idps)); then echo IDPS; elif ((ids)); then echo IDS; else echo stopped; fi
}
proxy_choice() { if systemctl is-enabled --quiet sslproxyd; then echo on; else echo off; fi; }
runtime_choice() {
    if [[ -f $RUNTIME_INTENT ]]; then
        read -r runtime_mode runtime_proxy < "$RUNTIME_INTENT" || return 1
        case $runtime_mode:$runtime_proxy in IDS:on|IDS:off|IDPS:on|IDPS:off|stopped:on|stopped:off) ;; *) echo 'ERROR: intención de ejecución no válida.' >&2; return 1 ;; esac
    else
        runtime_mode=$(saved_mode) || return 1
        runtime_proxy=$(proxy_choice)
    fi
}
status() {
    printf 'Modo guardado: %s; SSLproxy guardado: %s\n' "$(saved_mode)" "$(proxy_choice)"
    if runtime_choice; then printf 'Selección de ejecución: %s; SSLproxy=%s\n' "$runtime_mode" "$runtime_proxy"; fi
    local unit
    for unit in "${UNITS[@]}"; do
        printf '%s: actual=%s; arranque=%s\n' "$unit" "$(systemctl is-active "$unit" 2>/dev/null || true)" "$(systemctl is-enabled "$unit" 2>/dev/null || true)"
    done
    if iptables -w 5 -C FORWARD -m comment --comment harresi-suricata-fail-closed -j HARRESI_FAIL_CLOSED 2>/dev/null; then
        echo 'FAIL-CLOSED activo: tráfico de tránsito bloqueado; consulte el registro del monitor.'
    fi
    if [[ -f $RULES_RECOVERY ]]; then
        echo 'Recuperación de reglas pendiente: inicie/reinicie el modo seleccionado para verificar los ficheros restaurados.'
    fi
    if [[ -f $PACKAGE_RECOVERY ]]; then
        echo 'Recuperación de actualización pendiente: corrija la configuración y reintente dpkg --configure -a o reinicie el modo seleccionado.'
    fi
}
health() {
    local unit=$1 reply
    systemctl is-active --quiet "$unit" || return 1
    reply=$(timeout 5 suricatasc "$SOCKET_DIR/${unit}-command.socket" -c uptime) || return 1
    # Accept the documented JSON reply and legacy dictionary presentation.
    printf '%s' "$reply" | python3 -c 'import ast,json,sys; s=sys.stdin.read();
try: d=json.loads(s)
except ValueError: d=ast.literal_eval(s)
sys.exit(0 if d.get("return")=="OK" and isinstance(d.get("message"),(int,float)) else 1)' || return 1
    reply=$(timeout 10 suricatasc "$SOCKET_DIR/${unit}-command.socket" -c ruleset-stats) || return 1
    printf '%s' "$reply" | python3 -c 'import ast,json,sys; s=sys.stdin.read();
try: d=json.loads(s)
except ValueError: d=ast.literal_eval(s)
m=d.get("message",{}); sys.exit(0 if d.get("return")=="OK" and isinstance(m,dict) and int(m.get("rules_failed",m.get("failed",-1)))==0 else 1)'
}
proxy_health() {
    local pid listeners
    systemctl is-active --quiet sslproxyd || return 1
    pid=$(systemctl show -p MainPID --value sslproxyd)
    [[ $pid =~ ^[1-9][0-9]*$ ]] || return 1
    listeners=$(timeout 5 ss -H -ltnp 'sport = :8443') || return 1
    [[ $listeners == *"pid=$pid,"* ]]
}
wait_proxy() {
    local i
    for ((i=0;i<30;i++)); do proxy_health && return 0; sleep 1; done
    echo 'ERROR: SSLproxy no ofrece su listener TCP/8443.' >&2
    return 1
}
wait_health() {
    local unit=$1 i
    for ((i=0;i<30;i++)); do
        health "$unit" && return 0
        systemctl is-failed --quiet "$unit" && break
        sleep 1
    done
    echo "ERROR: $unit no está activo o no responde en su socket." >&2
    return 1
}
gate() {
    iptables -w 5 -N HARRESI_FAIL_CLOSED 2>/dev/null || true
    iptables -w 5 -C HARRESI_FAIL_CLOSED -j DROP 2>/dev/null || iptables -w 5 -A HARRESI_FAIL_CLOSED -j DROP || return 1
    iptables -w 5 -C FORWARD -m comment --comment harresi-suricata-fail-closed -j HARRESI_FAIL_CLOSED 2>/dev/null || iptables -w 5 -I FORWARD 1 -m comment --comment harresi-suricata-fail-closed -j HARRESI_FAIL_CLOSED || return 1
    iptables -w 5 -C INPUT -p tcp --dport 8443 -m comment --comment harresi-suricata-fail-closed -j HARRESI_FAIL_CLOSED 2>/dev/null || iptables -w 5 -I INPUT 1 -p tcp --dport 8443 -m comment --comment harresi-suricata-fail-closed -j HARRESI_FAIL_CLOSED || return 1
}
restore_selected() {
    local mode proxy unit context=${1:-manual}
    if [[ ${2:-} != locked ]]; then
        mkdir -p "$(dirname "$LOCK")"
        exec 9>"$LOCK"
        flock -x 9
    fi
    gate || return 1
    mode=$(saved_mode) || return 1
    if [[ $context != manual ]]; then
        runtime_choice || return 1
        if [[ $runtime_mode != stopped && $runtime_mode != "$mode" ]]; then
            echo 'ERROR: intención de ejecución y modo guardado incompatibles; FAIL-CLOSED se mantiene.' >&2
            return 1
        fi
        mode=$runtime_mode
        proxy=$runtime_proxy
    else
        proxy=off
        if systemctl is-active --quiet sslproxyd; then proxy=on; fi
    fi
    for unit in suricata_ids suricata_idps; do
        if systemctl is-active --quiet "$unit"; then
            if [[ $unit == suricata_ids && $mode != IDS || $unit == suricata_idps && $mode != IDPS ]]; then
                echo "ERROR: $unit activo no corresponde al modo guardado; FAIL-CLOSED se mantiene." >&2
                return 1
            fi
        fi
    done
    if [[ $context == manual ]]; then
        if [[ $mode == IDS ]] && ! systemctl is-active --quiet suricata_ids; then mode=stopped; fi
        if [[ $mode == IDPS ]] && ! systemctl is-active --quiet suricata_idps; then mode=stopped; fi
    fi
    if [[ $mode != IDPS || $proxy != on ]] && systemctl is-active --quiet suricata_mitm; then
        echo 'ERROR: MITM activo fuera de la combinación IDPS/SSLproxy; FAIL-CLOSED se mantiene.' >&2
        return 1
    fi
    if [[ $context != manual ]]; then
        "$FIREWALL" "$mode" "$proxy" guarded || return 1
        [[ $context != prepare ]] || return 0
    fi
    if [[ -f $PACKAGE_RECOVERY && ${3:-} != package-commit ]]; then
        if [[ $context == package ]]; then
            echo 'AVISO: perfil instalado; recuperación de actualización pendiente. FAIL-CLOSED se mantiene hasta configurar Suricata.' >&2
            return 0
        fi
        echo 'ERROR: recuperación de actualización pendiente; FAIL-CLOSED se mantiene.' >&2
        return 1
    fi
    if [[ $mode != stopped ]]; then
        unit=suricata_ids; [[ $mode != IDPS ]] || unit=suricata_idps
        if [[ $context == package ]]; then
            if ! health "$unit" 2>/dev/null; then
                echo "AVISO: perfil instalado; $unit aún no responde en su socket. FAIL-CLOSED se mantiene hasta verificar su recuperación." >&2
                return 0
            fi
        else
            wait_health "$unit" || return 1
        fi
    fi
    if [[ $mode == IDPS && $proxy == on ]]; then
        if [[ $context == package ]]; then
            if ! proxy_health || ! health suricata_mitm 2>/dev/null; then
                echo 'AVISO: perfil instalado; SSLproxy/MITM aún no están disponibles. FAIL-CLOSED se mantiene hasta verificar su recuperación.' >&2
                return 0
            fi
        else
            wait_proxy || return 1
            wait_health suricata_mitm || return 1
        fi
    fi
    if [[ -f $RULES_RECOVERY ]]; then
        echo 'ERROR: recuperación de reglas pendiente; FAIL-CLOSED se mantiene.' >&2
        return 1
    fi
    "$FIREWALL" "$mode" "$proxy"
}

restart_active_package() {
    local unit
    local -a running=()
    mkdir -p "$(dirname "$LOCK")"
    exec 9>"$LOCK"
    flock -x 9
    gate || return 1
    printf 'Actualización de Suricata pendiente de validación y reinicio.\n' > "$PACKAGE_RECOVERY.new" || return 1
    chmod 0600 "$PACKAGE_RECOVERY.new" || return 1
    mv -f "$PACKAGE_RECOVERY.new" "$PACKAGE_RECOVERY" || return 1
    # A running monitor may still contain its previous script in memory.
    # Reload it under the lock so a failed upgrade remains guarded afterward.
    systemctl daemon-reload || return 1
    systemctl try-restart suricata-monitor.service || return 1
    # Keep the gate and lock throughout validation and restart. The monitor
    # cannot reopen traffic between the old engine and the updated profiles.
    restore_selected prepare locked || return 1
    for unit in suricata_ids suricata_idps suricata_mitm; do
        if systemctl is-active --quiet "$unit"; then
            running+=("$unit")
            "$SURICATA_BIN" -T -c "$SURICATA_CONFIG_DIR/$unit.yaml" \
                --set unix-command.enabled=yes \
                --set "unix-command.filename=$SOCKET_DIR/$unit-command.socket" || return 1
        fi
    done
    for unit in "${running[@]}"; do
        systemctl try-restart "$unit" || return 1
    done
    for unit in "${running[@]}"; do
        wait_health "$unit" || return 1
    done
    if ((${#running[@]})); then
        restore_selected manual locked package-commit || return 1
    else
        # A deliberately stopped runtime stays stopped; an unexpectedly
        # unavailable selected engine stays gated without being started here.
        restore_selected package locked package-commit || return 1
        runtime_choice || return 1
        if [[ $runtime_mode != stopped ]]; then
            echo 'AVISO: motor seleccionado detenido; FAIL-CLOSED y la recuperación pendiente se mantienen. Inicie/reinicie el modo seleccionado para verificarlo.' >&2
            return 0
        fi
    fi
    rm -f "$PACKAGE_RECOVERY"
}

case ${1:-} in
    status) status; exit ;;
    failure-guard)
        unit=${2:-}
        runtime_choice || { gate; exit 1; }
        mode=$runtime_mode
        intended=0
        case $unit in
            suricata_ids) if [[ $mode == IDS ]] && systemctl is-enabled --quiet "$unit"; then intended=1; fi ;;
            suricata_idps) if [[ $mode == IDPS ]] && systemctl is-enabled --quiet "$unit"; then intended=1; fi ;;
            suricata_mitm|sslproxyd)
                if [[ $mode == IDPS && $runtime_proxy == on ]]; then intended=1; fi
                ;;
            *) echo 'Unidad no válida para la protección de fallo.' >&2; exit 1 ;;
        esac
        if ((intended)); then
            gate
            logger -t harresi-services -- "FAIL-CLOSED: $unit seleccionado se ha detenido; esperando recuperación verificada." || true
        fi
        exit ;;
    restore-selected) restore_selected; exit ;;
    restore-package) restore_selected package; exit ;;
    restart-active-package) restart_active_package; exit ;;
    mode) mode=${2:-}; case $mode in IDS|IDPS|stopped) ;; *) echo 'Uso: harresi-services mode IDS|IDPS|stopped [restart]' >&2; exit 1 ;; esac ;;
    sslproxy) action=${2:-}; case $action in start|stop|restart) ;; *) echo 'Uso: harresi-services sslproxy start|stop|restart' >&2; exit 1 ;; esac; mode=$(saved_mode) ;;
    *) echo 'Uso: harresi-services status|mode|sslproxy|restore-selected' >&2; exit 1 ;;
esac
mkdir -p "$(dirname "$LOCK")"
exec 9>"$LOCK"
flock -x 9
mode_requested=$mode
proxy=$(proxy_choice)
[[ ${1:-} != sslproxy ]] || { if [[ $action == stop ]]; then proxy=off; else proxy=on; fi; }
"$FIREWALL" "$mode" "$proxy" validate
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
# Validate the requested profiles without leaving live changes. The firewall
# helper validates before applying, then the transaction protects service gaps.
iptables-save > "$work/firewall"
[[ ! -f $RUNTIME_INTENT ]] || cp -p "$RUNTIME_INTENT" "$work/runtime"
declare -A enabled active
for unit in "${UNITS[@]}"; do
    enabled[$unit]=0; active[$unit]=0
    systemctl is-enabled --quiet "$unit" && enabled[$unit]=1
    systemctl is-active --quiet "$unit" && active[$unit]=1
done
rollback() {
    local unit failed=0
    trap - ERR HUP INT TERM
    echo 'ERROR: operación fallida; recuperando servicios y selección anteriores.' >&2
    for unit in "${UNITS[@]}"; do
        if ((enabled[$unit])); then systemctl enable "$unit" || failed=1; else systemctl disable "$unit" || failed=1; fi
        if ((active[$unit])); then systemctl start "$unit" || failed=1; else systemctl stop "$unit" || failed=1; fi
    done
    iptables-restore -w 5 < "$work/firewall" || failed=1
    if [[ -f $work/runtime ]]; then cp -p "$work/runtime" "$RUNTIME_INTENT" || failed=1; else rm -f "$RUNTIME_INTENT" || failed=1; fi
    for unit in suricata_ids suricata_idps suricata_mitm; do
        if ((active[$unit])); then wait_health "$unit" || failed=1; fi
    done
    if ((failed)); then
        gate || true
        printf 'Recuperación de servicios incompleta; inicie/reinicie el modo desde el menú.\n' > "$RULES_RECOVERY.new"
        chmod 0600 "$RULES_RECOVERY.new"
        mv -f "$RULES_RECOVERY.new" "$RULES_RECOVERY"
        echo 'CRÍTICO: recuperación incompleta; se conserva FAIL-CLOSED hasta una recuperación verificada.' >&2
    fi
    exit 1
}
trap rollback ERR HUP INT TERM
# Prevent traffic from bypassing inspection while changing a running mode.
gate
systemctl disable suricata_ids suricata_idps suricata_mitm
if [[ $mode == IDS ]]; then
    systemctl stop suricata_idps suricata_mitm
    systemctl enable suricata_ids
elif [[ $mode == IDPS ]]; then
    systemctl stop suricata_ids
    systemctl enable suricata_idps
else
    systemctl stop suricata_ids suricata_idps suricata_mitm
fi
if [[ $proxy == on ]]; then
    systemctl enable sslproxyd
    if [[ ${1:-} == sslproxy && $action == restart ]]; then systemctl restart sslproxyd; else systemctl start sslproxyd; fi
    wait_proxy
else
    systemctl disable --now sslproxyd
fi
if [[ $mode == IDPS && $proxy == on ]]; then
    systemctl enable suricata_mitm
    if [[ ${3:-} == restart || -f $RULES_RECOVERY || -f $PACKAGE_RECOVERY ]]; then systemctl restart suricata_mitm; else systemctl start suricata_mitm; fi
    wait_health suricata_mitm
else
    systemctl disable --now suricata_mitm
fi
if [[ $mode != stopped ]]; then
    unit=suricata_ids; [[ $mode != IDPS ]] || unit=suricata_idps
    if [[ ${3:-} == restart || -f $RULES_RECOVERY || -f $PACKAGE_RECOVERY ]]; then systemctl restart "$unit"; else systemctl start "$unit"; fi
    wait_health "$unit"
    systemctl enable --now suricata-aggregator suricata-monitor
    systemctl is-active --quiet suricata-aggregator
    systemctl is-active --quiet suricata-monitor
else
    systemctl disable --now suricata-aggregator
fi
# Redirects are installed only after the proxy and all intended engines are up.
"$FIREWALL" "$mode" "$proxy"
rm -f "$RULES_RECOVERY" "$PACKAGE_RECOVERY"
trap - ERR HUP INT TERM
echo "OK: selección guardada y aplicada: $mode; SSLproxy=$proxy."
