#!/usr/bin/env bash
# security/auth-log -- who is trying to log in, and from where
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_authlog)"

source_log=""
for f in /var/log/auth.log /var/log/secure; do
    [ -r "$f" ] && { source_log=$f; break; }
done

if [ -z "$source_log" ] && nv_have journalctl; then
    ui_info "$(t authlog_from_journal)"
    fails=$(journalctl -u ssh -u sshd --no-pager -n 500 2>/dev/null | grep -c 'Failed password')
    ips=$(journalctl -u ssh -u sshd --no-pager -n 500 2>/dev/null \
          | grep 'Failed password' | grep -oE 'from [0-9.]+' | awk '{print $2}' | sort | uniq -c | sort -rn | head -n 10)
else
    [ -n "$source_log" ] || { ui_err "$(t authlog_none)"; exit 1; }
    ui_kv "$(t backup_location)" "$source_log"
    fails=$(grep -c 'Failed password' "$source_log" 2>/dev/null || echo 0)
    ips=$(grep 'Failed password' "$source_log" 2>/dev/null \
          | grep -oE 'from [0-9.]+' | awk '{print $2}' | sort | uniq -c | sort -rn | head -n 10)
fi

ui_kv "$(t authlog_failures)" "${fails:-0}"
ui_section "$(t authlog_top_ips)"
if [ -z "$ips" ]; then
    ui_ok "$(t authlog_clean)"
else
    printf '%s\n' "$ips" | while read -r count ip; do
        printf '  %-18s %s\n' "$ip" "$count"
    done
    ui_blank
    ui_info "$(t authlog_block_hint)"
fi
ui_blank
exit 0
