#!/usr/bin/env bash
# web/vhosts -- every server block on disk, including ones not in the registry
#
# The point is adoption: on a machine that already runs websites, this shows
# what exists and what nhanhvps does not manage yet.
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_vhosts)" "$(t web_vhosts_dir)"

dir=/etc/nginx/sites-enabled
if [ ! -d "$dir" ]; then
    ui_info "$(t web_vhosts_none)"
    exit 0
fi

printf '  %-30s %-30s %s\n' "$(t col_domain)" "$(t web_vhost_root)" "$(t col_status)"
count=0; unmanaged=0
for f in "$dir"/*; do
    [ -e "$f" ] || continue
    count=$((count + 1))
    names=$(grep -hoE '^[[:space:]]*server_name[[:space:]]+[^;]+' "$f" 2>/dev/null \
            | sed -E 's/^[[:space:]]*server_name[[:space:]]+//' | tr -d ';' | head -n 1)
    [ -z "$names" ] && names='(default)'
    root=$(grep -hoE '^[[:space:]]*root[[:space:]]+[^;]+' "$f" 2>/dev/null \
           | sed -E 's/^[[:space:]]*root[[:space:]]+//' | tr -d ';' | head -n 1)
    [ -z "$root" ] && root='-'
    primary=$(printf '%s' "$names" | awk '{print $1}')
    if nv_site_exists "$primary"; then state="$(t web_managed)"
    else state="$(t web_unmanaged)"; unmanaged=$((unmanaged + 1)); fi
    printf '  %-30s %-30s %s\n' \
        "$(ui_trunc "$names" 28)" "$(ui_trunc "$root" 28)" "$state"
done

ui_blank
ui_kv "$(t web_vhosts_total)"   "$count"
[ "$unmanaged" -gt 0 ] && ui_warn "$(t web_vhosts_unmanaged "$unmanaged")"
exit 0
