#!/usr/bin/env bash
# security/fail2ban -- jail status, with an option to ensure the sshd jail
set -o pipefail
SELF=$(readlink -f "${BASH_SOURCE[0]}")
NV_BASE=$(cd "$(dirname "$SELF")/../../.." && pwd)
export NV_BASE
# shellcheck source=/dev/null
. "$NV_BASE/lib/core/bootstrap.sh"

nv_require_root || exit 1
ui_header "$(t sec_m_fail2ban)"

if ! nv_have fail2ban-client; then
    ui_warn "$(t f2b_not_installed)"
    ui_confirm "$(t f2b_install_q)" y || exit 0
    pkg_install fail2ban || { nv_fail 6104 "$(t f2b_install_failed)"; exit 1; }
fi

ui_kv "$(t svc_state)" "$(svc_status_word fail2ban 2>/dev/null || echo unknown)"

if fail2ban-client ping >/dev/null 2>&1; then
    ui_section "$(t f2b_jails)"
    jail_list=$(fail2ban-client status 2>/dev/null | sed -n 's/.*Jail list:[[:space:]]*//p')
    if [ -z "$jail_list" ] || [ "$jail_list" = "-" ]; then
        ui_info "$(t f2b_no_jail)"
    else
        for j in $(printf '%s' "$jail_list" | tr ',' ' '); do
            j=$(nv_trim "$j")
            [ -z "$j" ] && continue
            banned=$(fail2ban-client status "$j" 2>/dev/null | sed -n 's/.*Currently banned:[[:space:]]*//p')
            total=$(fail2ban-client status "$j" 2>/dev/null | sed -n 's/.*Total banned:[[:space:]]*//p')
            ui_kv "$j" "$(t f2b_jail_line "${banned:-0}" "${total:-0}")"
        done
    fi
else
    ui_warn "$(t f2b_not_running)"
fi

ui_blank
if ui_confirm "$(t f2b_ensure_ssh_jail)" n; then
    local_cfg=/etc/fail2ban/jail.local
    nv_backup_path "$local_cfg" fail2ban >/dev/null 2>&1 || true
    if [ -f "$local_cfg" ] && grep -q '^\[sshd\]' "$local_cfg"; then
        ui_ok "$(t f2b_already_configured)"
    else
        cat >"$local_cfg" <<'EOF'
# managed by nhanhvps -- sshd protection
[DEFAULT]
bantime  = 1h
findtime = 10m
maxretry = 5

[sshd]
enabled = true
port    = ssh
EOF
        ui_ok "$(t f2b_configured)"
        nv_trace fail2ban "sshd jail written to $local_cfg"
    fi
    svc_enable fail2ban
    svc_restart fail2ban
    sleep 1
    ui_kv "$(t svc_state)" "$(svc_status_word fail2ban)"
fi
ui_blank
exit 0
