#!/usr/bin/env bash
#
# onx-fail2ban-history — Son N ban/unban olayını DB'den çek + GeoIP lookup.
#
# Input: {"limit": 100, "jail": "sshd" (opsiyonel filter)}
# Output: {"events":[{jail,ip,country_code,action,event_at,failed_attempts}]}

set -euo pipefail

readonly DB="/var/lib/fail2ban/fail2ban.sqlite3"

input="$(cat 2>/dev/null || echo '{}')"
limit="$(echo "$input" | jq -r '.limit // 100')"
jail_filter="$(echo "$input" | jq -r '.jail // empty')"

[[ "$limit" =~ ^[0-9]+$ ]] || limit=100
(( limit > 500 )) && limit=500

if [[ ! -r "$DB" ]] || ! command -v sqlite3 &>/dev/null; then
    jq -nc '{ok:false,error:"fail2ban DB not readable"}' >&2
    exit 2
fi

# Build WHERE clause
where=""
if [[ -n "$jail_filter" ]] && [[ "$jail_filter" =~ ^[a-zA-Z0-9_-]+$ ]]; then
    where="WHERE jail = '$jail_filter'"
fi

# bans table → all "banned" events
tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT

sqlite3 -separator '|' "$DB" \
    "SELECT jail, ip, datetime(timeofban,'unixepoch') AS event_at,
            COALESCE(json_extract(data,'$.matches.length()'), 0) AS attempts,
            (CASE WHEN timeofban+bantime > strftime('%s','now') THEN 'banned' ELSE 'expired' END) AS action
     FROM bans $where
     ORDER BY timeofban DESC LIMIT $limit" 2>/dev/null > "$tmp" || true

events_json="["
first=1

while IFS='|' read -r jail ip event_at attempts action; do
    [[ -z "$ip" ]] && continue

    # GeoIP
    cc=""
    if [[ -d /var/lib/onox/geoip/cidrs ]] && command -v grepcidr &>/dev/null && [[ "$ip" != *:* ]]; then
        for f in /var/lib/onox/geoip/cidrs/*.txt; do
            [[ -f "$f" ]] || continue
            if grepcidr "$ip" "$f" &>/dev/null; then
                cc="$(basename "$f" .txt | tr '[:lower:]' '[:upper:]')"
                break
            fi
        done
    fi

    [[ $first -eq 0 ]] && events_json+=","
    first=0
    events_json+=$(jq -nc \
        --arg jail "$jail" --arg ip "$ip" --arg cc "$cc" \
        --arg event_at "$event_at" --arg action "$action" \
        --argjson attempts "${attempts:-0}" \
        '{jail:$jail,ip:$ip,country_code:$cc,event_at:$event_at,failed_attempts:$attempts,action:$action,reason:"fail2ban"}')
done < "$tmp"

events_json+="]"

jq -nc --argjson events "$events_json" --argjson limit "$limit" \
    '{ok:true,events:$events,limit:$limit}'
