#!/usr/bin/env bash
# =============================================================================
# onx-firewall-reload — Reload active firewall backend
#
# Input (stdin JSON):  {}  (no fields required)
# Output (stdout JSON): { "reloaded": true, "backend": "firewalld|ufw|nftables" }
#
# Deployed to: /usr/local/onoxsoft/bin/onx-firewall-reload
# =============================================================================

set -euo pipefail

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
# shellcheck source=_lib/common.sh
source "${SCRIPT_DIR}/_lib/common.sh"

require_root
onx_json_input

BACKEND=""
if command -v firewall-cmd >/dev/null 2>&1; then
    BACKEND="firewalld"
elif command -v ufw >/dev/null 2>&1; then
    BACKEND="ufw"
elif command -v nft >/dev/null 2>&1; then
    BACKEND="nftables"
else
    onx_die 2 "no firewall backend found"
fi

if [[ "${MOCK_MODE}" == "1" ]]; then
    jq -nc --arg b "${BACKEND}" '{reloaded:true, backend:$b, mock:true}'
    exit 0
fi

case "${BACKEND}" in
    firewalld)
        firewall-cmd --reload >/dev/null 2>&1 || onx_die 3 "firewall-cmd --reload failed"
        ;;
    ufw)
        ufw reload >/dev/null 2>&1 || onx_die 3 "ufw reload failed"
        ;;
    nftables)
        systemctl reload nftables 2>/dev/null \
            || systemctl restart nftables 2>/dev/null \
            || onx_die 3 "nftables reload/restart failed"
        ;;
esac

onx_audit "onx-firewall" "reload backend=${BACKEND}"
jq -nc --arg b "${BACKEND}" '{reloaded:true, backend:$b}'
