#!/usr/bin/env bash
# web/logs -- recent traffic and errors for one site
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"

ui_header "$(t web_m_logs)"

site_pick_domain "${1:-}" || exit $?
domain=$SITE_DOMAIN
acc="/var/log/nginx/$domain.access.log"
err="/var/log/nginx/$domain.error.log"

ui_section "$(t logs_summary)"
if [ -r "$acc" ]; then
    total=$(wc -l <"$acc")
    e5=$(awk '$9 ~ /^5/ {c++} END {print c+0}' "$acc" 2>/dev/null)
    e4=$(awk '$9 ~ /^4/ {c++} END {print c+0}' "$acc" 2>/dev/null)
    ui_kv "$(t logs_requests)" "$total"
    ui_kv "$(t logs_5xx)"      "${e5:-0}"
    ui_kv "$(t logs_4xx)"      "${e4:-0}"
else
    ui_info "$(t logs_no_access)"
fi

ui_section "$(t logs_errors)"
if [ -r "$err" ]; then tail -n 15 "$err" | sed 's/^/  /'; else ui_ok "$(t logs_no_errors)"; fi

ui_section "$(t logs_recent)"
[ -r "$acc" ] && tail -n 10 "$acc" | sed 's/^/  /'
ui_blank
exit 0
