#!/usr/bin/env bash
# site/debug-log -- read the WordPress debug log without opening a shell
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 site_m_debuglog)"

site_pick_domain "${1:-}" || exit $?
domain=$SITE_DOMAIN
root=$(nv_site_get "$domain" root_path "$(site_domain_root "$domain")")
log="$root/wp-content/debug.log"

if [ ! -f "$log" ]; then
    ui_info "$(t dbg_none)"
    ui_info "$(t dbg_hint)"
    exit 0
fi

ui_kv "$(t backup_location)" "$log"
ui_kv "$(t col_size)" "$(du -h "$log" | cut -f1)"
ui_section "$(t logs_recent)"
tail -n 30 "$log" | sed 's/^/  /'
ui_blank

if ui_confirm "$(t dbg_clear_q)" n; then
    nv_backup_path "$log" debug-log >/dev/null 2>&1 || true
    : >"$log"
    chown "$(stat -c '%U:%G' "$root")" "$log" 2>/dev/null || true
    nv_trace debug-log "cleared $domain"
    ui_ok "$(t dbg_cleared)"
fi
exit 0
