#!/usr/bin/env bash
# =============================================================================
# onx-fail2ban-status — Report fail2ban global / per-jail status
#
# Input (stdin JSON):
#   { "jail": "sshd" }      -- optional; omit for global status
#
# Output (stdout JSON):
#   Global:
#     { "jails":["sshd","apache-auth"], "count":2,
#       "running": true, "version": "1.0.2" }
#   Per-jail:
#     { "jail":"sshd", "currently_failed":2, "currently_banned":1,
#       "total_failed":47, "total_banned":12, "banned_ips":["1.2.3.4"],
#       "file_list":["/var/log/secure"] }
#
# Deployed to: /usr/local/onoxsoft/bin/onx-fail2ban-status
# =============================================================================

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

JAIL=$(onx_json_field "jail" "")
if [[ -n "${JAIL}" ]]; then
    [[ "${JAIL}" =~ ^[a-zA-Z0-9_-]{1,40}$ ]] || onx_die 1 "invalid jail '${JAIL}'"
fi

# ── MOCK / no fail2ban-client installed ──────────────────────────────────────
if [[ "${MOCK_MODE}" == "1" ]] || ! command -v fail2ban-client >/dev/null 2>&1; then
    if [[ -z "${JAIL}" ]]; then
        jq -nc '{
            running:true, version:"1.0.2",
            jails:["sshd","pure-ftpd","panel-login","recidive"],
            count:4
        }'
    else
        jq -nc --arg j "${JAIL}" '{
            jail:$j,
            currently_failed:2,
            currently_banned:1,
            total_failed:47,
            total_banned:12,
            banned_ips:["1.2.3.4","5.6.7.8"],
            file_list:["/var/log/secure"]
        }'
    fi
    exit 0
fi

if [[ -z "${JAIL}" ]]; then
    RAW=$(fail2ban-client status 2>/dev/null || echo "")
    JAIL_LIST=$(printf '%s' "${RAW}" | awk -F':' '/Jail list/{print $2}' | sed 's/,/\n/g' | sed 's/^\s*//;s/\s*$//' \
        | jq -R -s -c 'split("\n") | map(select(length>0))')
    VERSION=$(fail2ban-client version 2>/dev/null || echo "unknown")
    RUNNING="false"
    systemctl is-active --quiet fail2ban 2>/dev/null && RUNNING="true"
    COUNT=$(printf '%s' "${JAIL_LIST}" | jq 'length')
    jq -nc --argjson jails "${JAIL_LIST}" --arg v "${VERSION}" \
        --argjson r "${RUNNING}" --argjson c "${COUNT}" \
        '{running:$r, version:$v, jails:$jails, count:$c}'
    exit 0
fi

RAW=$(fail2ban-client status "${JAIL}" 2>&1 || echo "")
CUR_FAIL=$(printf '%s' "${RAW}" | awk -F':' '/Currently failed/{gsub(/^\s+|\s+$/,"",$2); print $2}' | head -1)
TOT_FAIL=$(printf '%s' "${RAW}" | awk -F':' '/Total failed/   {gsub(/^\s+|\s+$/,"",$2); print $2}' | head -1)
CUR_BAN=$( printf '%s' "${RAW}" | awk -F':' '/Currently banned/{gsub(/^\s+|\s+$/,"",$2); print $2}' | head -1)
TOT_BAN=$( printf '%s' "${RAW}" | awk -F':' '/Total banned/   {gsub(/^\s+|\s+$/,"",$2); print $2}' | head -1)
BAN_IPS=$( printf '%s' "${RAW}" | awk -F':' '/Banned IP list/  {gsub(/^\s+|\s+$/,"",$2); print $2}' | head -1)
FILE_LIST=$(printf '%s' "${RAW}" | awk -F':' '/File list/      {gsub(/^\s+|\s+$/,"",$2); print $2}' | head -1)

BAN_IPS_JSON=$(printf '%s' "${BAN_IPS:-}" | tr ' ' '\n' | jq -R -s -c 'split("\n") | map(select(length>0))')
FILE_JSON=$(printf '%s' "${FILE_LIST:-}" | tr ' ' '\n' | jq -R -s -c 'split("\n") | map(select(length>0))')

jq -nc \
    --arg j "${JAIL}" \
    --argjson cf "${CUR_FAIL:-0}" \
    --argjson tf "${TOT_FAIL:-0}" \
    --argjson cb "${CUR_BAN:-0}" \
    --argjson tb "${TOT_BAN:-0}" \
    --argjson ips "${BAN_IPS_JSON}" \
    --argjson files "${FILE_JSON}" \
    '{jail:$j, currently_failed:$cf, total_failed:$tf,
      currently_banned:$cb, total_banned:$tb,
      banned_ips:$ips, file_list:$files}'
