#!/usr/bin/env bash
# ──────────────────────────────────────────────────────────────
#  check_ban_status.sh
#
#  Queries the manual-Jail jail inside the running fail2ban
#  container and optionally unbans a specific IP.
#
#  Usage:
#    bash Docker/check_ban_status.sh
#    bash Docker/check_ban_status.sh --unban 192.168.100.99
#
#  Requirements:
#    The bangui-fail2ban-dev container must be running.
#    (docker compose -f Docker/compose.debug.yml up -d fail2ban)
# ──────────────────────────────────────────────────────────────

set -euo pipefail

readonly CONTAINER="bangui-fail2ban-dev"
readonly JAIL="manual-Jail"

# ── Helper: run a fail2ban-client command inside the container ─
f2b() {
    docker exec "${CONTAINER}" fail2ban-client "$@"
}

# ── Parse arguments ───────────────────────────────────────────
UNBAN_IP=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        --unban)
            if [[ -z "${2:-}" ]]; then
                echo "ERROR: --unban requires an IP address argument." >&2
                exit 1
            fi
            UNBAN_IP="$2"
            shift 2
            ;;
        *)
            echo "ERROR: Unknown argument: '$1'" >&2
            echo "Usage: $0 [--unban <IP>]" >&2
            exit 1
            ;;
    esac
done

# ── Unban mode ────────────────────────────────────────────────
if [[ -n "${UNBAN_IP}" ]]; then
    echo "Unbanning ${UNBAN_IP} from jail '${JAIL}' ..."
    f2b set "${JAIL}" unbanip "${UNBAN_IP}"
    echo "Done. '${UNBAN_IP}' has been removed from the ban list."
    echo ""
fi

# ── Jail status ───────────────────────────────────────────────
echo "═══════════════════════════════════════════"
echo "  Jail status: ${JAIL}"
echo "═══════════════════════════════════════════"
f2b status "${JAIL}"

# ── Banned IPs with timestamps ────────────────────────────────
echo ""
echo "═══════════════════════════════════════════"
echo "  Banned IPs with timestamps: ${JAIL}"
echo "═══════════════════════════════════════════"
f2b get "${JAIL}" banip --with-time || echo "(no IPs currently banned)"
