#!/usr/bin/env bash
# web/maintenance -- serve a maintenance page while keeping the site intact
#
# Toggling the flag regenerates the vhost; the switch itself is a marker file,
# so turning maintenance on is instant and does not need a config reload.
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 web_m_maintenance)"

site_pick_domain "${1:-}" || exit $?
domain=$SITE_DOMAIN
cur=$(nv_site_get "$domain" maintenance 0)
root=$(nv_site_get "$domain" root_path "$(site_domain_root "$domain")")
marker="$root/.nhanhvps-maintenance"

ui_kv "$(t col_domain)" "$domain"
ui_kv "$(t web_state)"  "$([ "$cur" = "1" ] && t state_enabled || t state_disabled)"
ui_kv "$(t site_root)"  "$root"
ui_blank

if [ "$cur" = "1" ]; then
    ui_confirm "$(t web_maint_off_q)" y || exit 0
    rm -f "$marker"
    new=$(site_toggle "$domain" maintenance) || { nv_fail 3201 "$(t site_fail_nginx)"; exit 1; }
    ui_ok "$(t web_maint_off)"
else
    ui_confirm "$(t web_maint_on_q)" n || exit 0
    new=$(site_toggle "$domain" maintenance) || { nv_fail 3201 "$(t site_fail_nginx)"; exit 1; }
    if [ "$new" = "1" ]; then
        : >"$marker"
        chown "$(site_web_user "$domain"):" "$marker" 2>/dev/null || true
        ui_ok "$(t web_maint_on)"
        ui_info "$(t web_maint_note)"
    fi
fi
exit 0
