#!/usr/bin/env bash
# nhanhvps -- server control panel
# Copyright (c) 2026 nhanhvps contributors
# SPDX-License-Identifier: GPL-2.0-only

set -o pipefail

SELF=$(readlink -f "${BASH_SOURCE[0]}")
SELF_DIR=$(dirname "$SELF")

if [ -r "$SELF_DIR/../lib/core/bootstrap.sh" ]; then
    NV_BASE=$(cd "$SELF_DIR/.." && pwd)              # running from source tree
elif [ -r "/usr/lib/nhanhvps/lib/core/bootstrap.sh" ]; then
    NV_BASE="/usr/lib/nhanhvps"                     # installed layout
else
    printf 'nhanhvps: installation is incomplete (lib/core not found)\n' >&2
    exit 1
fi
export NV_BASE

# shellcheck source=/dev/null
. "$NV_BASE/lib/core/bootstrap.sh"

NV_VERSION=$(cat "$NV_BASE/VERSION" 2>/dev/null || echo '0.0.0-dev')

usage() {
    cat <<EOF
nhanhvps $NV_VERSION -- server control panel (Ubuntu 24.04 LTS)

USAGE
  nhanhvps                          open the interactive menu
  nhanhvps preflight [--dry-run]    inspect the server and print the install plan
  nhanhvps install [--yes]          run preflight, then install
  nhanhvps list                     list available modules
  nhanhvps run GROUP/NAME [args]    run one module non-interactively
  nhanhvps site list|create|remove  manage websites
  nhanhvps backup <domain>          snapshot one site (database + files)
  nhanhvps ssl <domain>             show or issue a certificate
  nhanhvps doctor                   health summary for every site
  nhanhvps lang vi|en               switch interface language
  nhanhvps diagnose                 collect support bundle
  nhanhvps update                   update the panel through apt
  nhanhvps version                  print version

RUN AS
  root (most commands change system state)
EOF
}

main_menu() {
    local M="$NV_MODULES_DIR"
    nv_menu_reset "$(t app_title)" "v$NV_VERSION - $(nv_os_pretty)"
    nv_menu_item "$(t menu_group_site)"    "$M/site/menu"
    nv_menu_item "$(t menu_group_web)"     "$M/web/menu"
    nv_menu_item "$(t menu_group_php)"     "$M/php/menu"
    nv_menu_item "$(t menu_group_database)" "$M/database/menu"
    nv_menu_item "$(t menu_group_cache)"   "$M/cache/menu"
    nv_menu_item "$(t menu_group_ssl)"     "$M/ssl/menu"
    nv_menu_item "$(t menu_group_backup)"  "$M/backup/menu"
    nv_menu_item "$(t menu_group_security)" "$M/security/menu"
    nv_menu_item "$(t menu_group_system)"  "$M/system/menu"
    nv_menu_item "$(t menu_group_tool)"    "$M/tool/menu"
    nv_menu_item "$(t menu_group_migrate)" "$M/migrate/menu"
    nv_menu_run
}

cmd_list() {
    local d id group title_key
    printf '%-22s %-12s %s\n' ID GROUP TITLE
    for d in $(nv_module_dirs); do
        id=$(nv_module_id "$d")
        group=$(nv_module_meta "$d" group -)
        title_key=$(nv_module_meta "$d" title_key -)
        printf '%-22s %-12s %s\n' "$id" "$group" "$(t "$title_key")"
    done
}

cmd_site() {
    local sub=${1:-list}; shift 2>/dev/null || true
    case $sub in
        list)
            local domain php ssl health
            ui_header "$(t site_list_title)"
            if [ "$(nv_site_count)" -eq 0 ]; then
                ui_info "$(t site_none)"
                return 0
            fi
            printf '  %-34s %-8s %-12s %s\n' DOMAIN PHP SSL STATUS
            while IFS=$'\t' read -r domain php ssl health; do
                printf '  %-34s %-8s %-12s %s\n' "$domain" "$php" "$ssl" "$health"
            done < <(nv_site_summary)
            ;;
        create)  nv_module_run "site/wp-create" "$@" ;;
        remove)  nv_module_run "site/remove" "$@" ;;
        repair)  nv_module_run "site/repair" "$@" ;;
        *)       nv_fail 9193 "unknown site subcommand: $sub" ;;
    esac
}

main() {
    local cmd=${1:-}
    [ $# -gt 0 ] && shift

    case $cmd in
        ''|menu)   nv_require_root || exit 1; main_menu ;;
        version|--version|-v) printf 'nhanhvps %s\n' "$NV_VERSION" ;;
        help|--help|-h) usage ;;
        list)      cmd_list ;;
        run)       [ -z "${1:-}" ] && { usage; exit 1; }; nv_module_run "$@" ;;
        site)      cmd_site "$@" ;;
        lang)
            local l=${1:-}
            case $l in
                vi|en) nv_conf_set_persist lang "$l"; nv_i18n_set "$l"
                       ui_ok "$(t lang_changed "$l")" ;;
                *)     nv_fail 9194 "usage: nhanhvps lang vi|en" ;;
            esac
            ;;
        backup)
            [ -z "${1:-}" ] && { usage; exit 1; }
            nv_module_run "backup/now" "$@" ;;
        ssl)
            [ -z "${1:-}" ] && { usage; exit 1; }
            nv_module_run "ssl/status" "$@" ;;
        doctor)
            # read-only health sweep over every registered site
            local domain php ssl health rc=0
            ui_header "$(t site_health_title)"
            if [ "$(nv_site_count)" -eq 0 ]; then
                ui_info "$(t site_none)"
                return 0
            fi
            while IFS=$'\t' read -r domain php ssl health; do
                case $health in
                    ok)       ui_ok "$domain" ;;
                    no-vhost) ui_warn "$domain -- $(t doctor_no_vhost)"; rc=1 ;;
                    no-root)  ui_warn "$domain -- $(t doctor_no_root)";  rc=1 ;;
                    missing)  ui_err  "$domain -- $(t doctor_missing)"; rc=1 ;;
                    *)        ui_warn "$domain -- $health"; rc=1 ;;
                esac
            done < <(nv_site_summary)
            return $rc ;;
        update)    nv_module_run "tool/update" ;;
        preflight) bash "$NV_BASE/install/preflight.sh" "$@" ;;
        install)   bash "$NV_BASE/install/install.sh" "$@" ;;
        diagnose)  bash "$NV_BASE/install/diagnose.sh" "$@" ;;
        *)         nv_fail 9195 "unknown command: $cmd (try --help)" ;;
    esac
}

main "$@"
