#!/usr/bin/env bash
# ssl/status -- certificate inventory with a renewal warning window
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"

WARN_DAYS=${NV_SSL_WARN_DAYS:-21}
ui_header "$(t ssl_m_status)" "$(t ssl_warn_window "$WARN_DAYS")"

live=/etc/letsencrypt/live
if [ ! -d "$live" ]; then
    ui_info "$(t ssl_none_issued)"
    exit 0
fi

printf '  %-34s %-12s %-8s %s\n' \
    "$(t col_domain)" "$(t ssl_expires)" "$(t ssl_days_left)" "$(t col_status)"

found=0
for d in "$live"/*/; do
    [ -d "$d" ] || continue
    name=$(basename "$d")
    cert="$d/fullchain.pem"
    [ -r "$cert" ] || continue
    found=1
    end=$(openssl x509 -enddate -noout -in "$cert" 2>/dev/null | cut -d= -f2)
    end_epoch=$(date -d "$end" +%s 2>/dev/null || echo 0)
    now=$(date +%s)
    days=$(( (end_epoch - now) / 86400 ))
    if [ "$days" -lt 0 ]; then state='EXPIRED'
    elif [ "$days" -le "$WARN_DAYS" ]; then state='renew-soon'
    else state='valid'; fi
    printf '  %-34s %-12s %-8s %s\n' \
        "$name" "$(date -d "$end" '+%Y-%m-%d' 2>/dev/null || echo '?')" "$days" "$state"
done

if [ "$found" = "0" ]; then
    ui_info "$(t ssl_none_issued)"
fi

if nv_have systemctl; then
    t=$(systemctl list-timers --all 2>/dev/null | grep -c 'certbot')
    [ "$t" -gt 0 ] && ui_ok "$(t ssl_auto_renew_on)" || ui_warn "$(t ssl_auto_renew_off)"
fi
ui_blank
exit 0
