#!/usr/bin/env bash
#
# onx-fail2ban-whitelist-write — Global ignoreip listesini /etc/fail2ban/jail.local'a yaz.
#
# Input: {"ips": ["1.2.3.4", "10.0.0.0/8", "2001:db8::1"]}
# Output: {"ok":true,"count":N,"applied":true,"reloaded":true}
#
# Strategy:
#   - /etc/fail2ban/jail.local içinde [DEFAULT] section'ı yönet
#   - "ignoreip" satırını "127.0.0.1/8 ::1" + verilen IP'lerle güncelle
#   - reload

set -euo pipefail

input="$(cat)"
ips_count="$(echo "$input" | jq '.ips // [] | length')"

readonly JAIL_LOCAL="/etc/fail2ban/jail.local"
readonly LOG_TAG="onox-fail2ban-wl"

# IP listesini topla (her zaman localhost dahil)
declare -a all_ips=("127.0.0.1/8" "::1")

if (( ips_count > 0 )); then
    while IFS= read -r ip; do
        [[ -z "$ip" ]] && continue
        # Basic validate — skip bad ones silently (UI catches them, this is belt+suspenders)
        if [[ "$ip" == *:* ]]; then
            [[ "$ip" =~ ^[0-9a-fA-F:]+(/[0-9]{1,3})?$ ]] && all_ips+=("$ip")
        else
            [[ "$ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}(/[0-9]{1,2})?$ ]] && all_ips+=("$ip")
        fi
    done < <(echo "$input" | jq -r '.ips[]?')
fi

# Build ignoreip value (space-separated)
ignoreip_value="$(IFS=' '; echo "${all_ips[*]}")"

# Ensure JAIL_LOCAL exists with [DEFAULT] section
if [[ ! -f "$JAIL_LOCAL" ]]; then
    cat > "$JAIL_LOCAL" <<EOF
# Managed by ONOX panel — do not edit "ignoreip" line manually,
# use the Whitelist UI under Security → fail2ban.
[DEFAULT]
ignoreip = $ignoreip_value
EOF
else
    # Update existing ignoreip or add new
    if grep -qE '^[[:space:]]*ignoreip[[:space:]]*=' "$JAIL_LOCAL"; then
        # Replace existing line (escape special chars in the value)
        escaped_value="$(echo "$ignoreip_value" | sed 's/[\/&]/\\&/g')"
        sed -i -E "s|^([[:space:]]*ignoreip[[:space:]]*=).*|\1 ${escaped_value}|" "$JAIL_LOCAL"
    else
        # Add under [DEFAULT] section if present, else create section
        if grep -qE '^\[DEFAULT\]' "$JAIL_LOCAL"; then
            sed -i -E "/^\[DEFAULT\]/a ignoreip = ${ignoreip_value}" "$JAIL_LOCAL"
        else
            echo -e "\n[DEFAULT]\nignoreip = ${ignoreip_value}" >> "$JAIL_LOCAL"
        fi
    fi
fi

# Reload fail2ban
reloaded=true
if command -v fail2ban-client &>/dev/null; then
    fail2ban-client reload 2>/dev/null || reloaded=false
fi

logger -t "$LOG_TAG" "Whitelist updated: ${#all_ips[@]} entries"

jq -nc --argjson count "${#all_ips[@]}" --argjson reloaded "$reloaded" \
    '{ok:true,count:$count,applied:true,reloaded:$reloaded}'
