#!/usr/bin/env bash
#
# onx-fail2ban-unban-all — Belirtilen jail'deki tüm aktif banları kaldır.
#
# Input: {"jail": "sshd"}
# Output: {"ok":true,"jail":"...","unbanned_count":N}

set -euo pipefail

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

if [[ -z "$jail" ]] || ! [[ "$jail" =~ ^[a-zA-Z0-9_-]{1,40}$ ]]; then
    jq -nc '{ok:false,error:"jail required"}' >&2
    exit 1
fi

if ! command -v fail2ban-client &>/dev/null; then
    jq -nc '{ok:false,error:"fail2ban-client not installed"}' >&2
    exit 2
fi

# Count before
count_before=0
if banned_raw="$(fail2ban-client status "$jail" 2>/dev/null | grep "Banned IP list" | cut -d: -f2 || true)"; then
    if [[ -n "$banned_raw" ]]; then
        count_before=$(echo "$banned_raw" | tr ',' '\n' | grep -cE '\S' || true)
    fi
fi

# Use fail2ban-client unban --all per jail
# Modern fail2ban (>=0.10): set <jail> unban --all
# Old fail2ban: iterate
if ! fail2ban-client set "$jail" unban --all &>/dev/null; then
    # Fallback: loop
    if banned_raw="$(fail2ban-client status "$jail" 2>/dev/null | grep "Banned IP list" | cut -d: -f2)"; then
        IFS=',' read -ra ips <<<"$(echo "$banned_raw" | tr -d ' \t')"
        for ip in "${ips[@]}"; do
            [[ -z "$ip" ]] && continue
            fail2ban-client set "$jail" unbanip "$ip" &>/dev/null || true
        done
    fi
fi

logger -t "onox-fail2ban" "Unban all on $jail (was $count_before)"

jq -nc --arg jail "$jail" --argjson count "$count_before" \
    '{ok:true,jail:$jail,unbanned_count:$count}'
