#!/usr/bin/env bash
# Fake ufw: simulates loading after.rules with iptables-restore
# --noflush (only declared chains are flushed, then filled).
set -euo pipefail
printf 'ufw %s\n' "$*" >>"$STUB_LOG"
kernel="$STUB_STATE/kernel"
touch "$kernel"
case "${1:-}" in
    status)
        # Like the real one (Python gettext), LANGUAGE wins over LC_ALL.
        if [[ "${LANGUAGE:-}" == fr* ]]; then
            echo "État : actif"
            exit 0
        fi
        if [[ "${STUB_UFW_INACTIVE:-0}" == 1 ]]; then
            echo "Status: inactive"
        elif [[ "${2:-}" == verbose && -n "${STUB_UFW_STATUS:-}" ]]; then
            cat "$STUB_UFW_STATUS"
        else
            echo "Status: active"
        fi
        ;;
    version) echo "ufw 0.36.2" ;;
    reload)
        [[ "${STUB_UFW_RELOAD_RC:-0}" == 0 ]] || exit "$STUB_UFW_RELOAD_RC"
        [[ "${STUB_UFW_RELOAD_NOOP:-0}" == 1 ]] && exit 0
        rules="$FENCE_ROOT/etc/ufw/after.rules"
        declared="$(grep -E '^:[^ ]+ ' "$rules" | sed 's/^:\([^ ]*\) .*/\1/' | sort -u || true)"
        tmp="$(mktemp)"
        while IFS= read -r line; do
            chain="$(printf '%s' "$line" | awk '{print $2}')"
            if ! grep -qxF -- "$chain" <<<"$declared"; then
                printf '%s\n' "$line"
            fi
        done <"$kernel" >"$tmp"
        grep -E '^-A ' "$rules" >>"$tmp" || true
        if [[ "${STUB_UFW_DROP_C2H:-0}" == 1 ]]; then
            grep -v -- '-j ACCEPT$' "$tmp" >"$tmp.2" || true
            mv "$tmp.2" "$tmp"
        fi
        mv "$tmp" "$kernel"
        ;;
    show)
        [[ -n "${STUB_UFW_ADDED:-}" ]] && cat "$STUB_UFW_ADDED"
        ;;
    *) exit 1 ;;
esac
