#!/usr/bin/env bash
#
# onx-firewall-threat-toggle — Tehdit listesi setini enable/disable.
#
# Input (stdin JSON): {"slug": "spamhaus_drop", "action": "enable"|"disable"}
# Output: {"ok":true,"slug":"...","action":"...","set_emptied":bool}

set -euo pipefail

input="$(cat)"
slug="$(echo "$input" | jq -r '.slug // empty')"
action="$(echo "$input" | jq -r '.action // empty')"

if [[ -z "$slug" || -z "$action" ]]; then
    jq -nc '{ok:false,error:"slug and action required"}' >&2
    exit 1
fi

if [[ "$action" != "enable" && "$action" != "disable" ]]; then
    jq -nc '{ok:false,error:"action must be enable|disable"}' >&2
    exit 1
fi

if ! [[ "$slug" =~ ^[a-z0-9_]+$ ]]; then
    jq -nc '{ok:false,error:"invalid slug"}' >&2
    exit 1
fi

readonly SET_V4="onox-threat-${slug//_/-}"
readonly SET_V6="onox-threat-${slug//_/-}-v6"

set_emptied=false

if [[ "$action" == "disable" ]]; then
    # Set'i flush et (silmiyoruz — re-enable hızlı olsun)
    if nft list set inet onox "$SET_V4" &>/dev/null; then
        nft flush set inet onox "$SET_V4"
        set_emptied=true
    fi
    if nft list set inet onox "$SET_V6" &>/dev/null; then
        nft flush set inet onox "$SET_V6"
    fi
    logger -t "onox-threat-toggle" "Disabled $slug (sets flushed)"
else
    # Sadece infra'yı hazırla — gerçek IP'leri threat-sync getirir
    nft list table inet onox &>/dev/null || nft add table inet onox
    nft list chain inet onox threat_in &>/dev/null || \
        nft 'add chain inet onox threat_in { type filter hook input priority -50; }'
    nft list set inet onox "$SET_V4" &>/dev/null || \
        nft "add set inet onox $SET_V4 { type ipv4_addr; flags interval; auto-merge; }"
    logger -t "onox-threat-toggle" "Enabled $slug (set ready, sync needed)"
fi

jq -nc --arg slug "$slug" --arg action "$action" --argjson set_emptied "$set_emptied" \
    '{ok:true,slug:$slug,action:$action,set_emptied:$set_emptied}'
