#!/usr/bin/env bash
# =====================================================================
# NgStack Installer 2.0 — Rexar Systems
#
#   wget https://ngstack.net/installer -O ngstack-installer && chmod +x ngstack-installer && sudo ./ngstack-installer
#
# Unattended:
#   sudo NGSTACK_LICENSE=RX-... NGSTACK_ADMIN_USER=me NGSTACK_ADMIN_PASS='...' \
#        NGSTACK_DOMAIN=panel.example.com NGSTACK_EMAIL=you@example.com ./ngstack-installer
#
# Optional: NGSTACK_PANEL_PORT (default 38888), NGSTACK_FREE_PORTS=1 (stop apache/nginx
# using 80/443 without asking).
#
# What it guarantees:
#   * ports 80/443 belong to NgStack's nginx (your sites); the panel gets its own port
#   * the panel is HTTPS-only (Let's Encrypt for a domain, self-signed for the IP)
#   * internal ports (UI, agent) listen on 127.0.0.1 only
#   * the admin password is stored hashed by the panel — never in container env/logs
#   * "installed successfully" is printed only after the panel actually answers
# =====================================================================
set -Eeuo pipefail
umask 077

readonly INSTALLER_VERSION="2.0"
readonly LOG=/var/log/ngstack-install.log
readonly LICENSE_API="${NGSTACK_LICENSE_API:-https://license.ngstack.net/api/license/verify}"
TEST_MODE=0 # 1 only for local tests against a mock license server
[ -n "${NGSTACK_LICENSE_API:-}" ] && TEST_MODE=1
readonly TEST_MODE
PANEL_PORT="${NGSTACK_PANEL_PORT:-38888}"
UI_PORT=3000
AGENT_PORT=8088
DOMAIN=""
EMAIL=""
SERVER_IP=""
CLOUD=""
SSL_MODE="self-signed"

GREEN=$'\e[32m'; YELLOW=$'\e[33m'; RED=$'\e[31m'; BLUE=$'\e[34m'; CYAN=$'\e[36m'; BOLD=$'\e[1m'; NC=$'\e[0m'

ok()   { echo -e "${GREEN}✓${NC} $*"; echo "[ok] $*" >> "$LOG"; }
info() { echo -e "${CYAN}•${NC} $*"; echo "[..] $*" >> "$LOG"; }
warn() { echo -e "${YELLOW}⚠${NC}  $*"; echo "[warn] $*" >> "$LOG"; }
PREV_SAVED=0 # 1 while the previous install is parked (stopped + renamed) during a reinstall
fail() {
    trap - ERR
    echo -e "\n${RED}✗ $*${NC}" >&2
    echo "[fail] $*" >> "$LOG"
    [ "$PREV_SAVED" = "1" ] && restore_previous
    echo -e "  Full log: ${BOLD}$LOG${NC}   Support: https://ngstack.net" >&2
    exit 1
}

# a failed reinstall must never leave the server without its panel
restore_previous() {
    local c
    echo -e "${YELLOW}↩ Restoring your previous NgStack containers…${NC}" >&2
    for c in ngstack-nginx ngstack-panel ngstack-updater; do
        if docker ps -a --format '{{.Names}}' | grep -qx "${c}__prev"; then
            docker rm -f "$c" >/dev/null 2>&1 || true
            docker rename "${c}__prev" "$c" >/dev/null 2>&1 && docker start "$c" >/dev/null 2>&1 || true
        fi
    done
    PREV_SAVED=0
    echo -e "${GREEN}✓ Previous installation restored and running.${NC}" >&2
}
trap 'fail "Unexpected error on line $LINENO (see the log)."' ERR

# run quietly; on failure show the tail of the output
quiet() {
    local out
    if ! out=$("$@" 2>&1); then
        echo "$out" >> "$LOG"
        echo "$out" | tail -n 8 >&2
        return 1
    fi
    echo "$out" >> "$LOG"
}

# a real terminal we can ask questions on (/dev/tty can exist without being usable)
has_tty() { ( : < /dev/tty ) 2>/dev/null; }

# prompts read from the terminal even when the script is piped (curl | bash)
ask() {
    local prompt="$1" var="$2" silent="${3:-}" reply=""
    if ! has_tty; then fail "No terminal for questions. Use the NGSTACK_* variables for an unattended install."; fi
    if [ "$silent" = "silent" ]; then
        IFS= read -r -s -p "$prompt" reply < /dev/tty; echo > /dev/tty
    else
        IFS= read -r -p "$prompt" reply < /dev/tty
    fi
    printf -v "$var" '%s' "$reply"
}

yes_no() { # yes_no "question" default(y|n)
    local a; ask "$1" a
    a="${a:-$2}"
    case "$a" in [Yy]*|ن*) return 0 ;; *) return 1 ;; esac
}

banner() {
    clear || true
    echo -e "${BLUE}=======================================================${NC}"
    echo -e "${GREEN}${BOLD}        NgStack Installer ${INSTALLER_VERSION} — Rexar Systems${NC}"
    echo -e "${BLUE}=======================================================${NC}\n"
}

# ---------------------------------------------------------------------
# 1. System checks
# ---------------------------------------------------------------------
# Other hosting panels own ports 80/443 and restart their web server on their own.
# Installing next to one would take their sites offline and the two panels would
# fight over the ports, so stop before anything on the server is touched.
detect_hosting_panel() {
    local found=""
    if   [ -e /usr/local/cpanel/cpanel ] || [ -e /usr/local/cpanel/version ]; then found="cPanel / WHM"
    elif [ -e /usr/local/psa/version ];                                        then found="Plesk"
    elif [ -e /usr/local/directadmin/directadmin ];                            then found="DirectAdmin"
    elif [ -d /usr/local/CyberCP ];                                            then found="CyberPanel"
    elif [ -d /www/server/panel/class ];                                       then found="aaPanel"
    elif [ -d /usr/local/hestia ];                                             then found="HestiaCP"
    elif [ -d /usr/local/vesta ];                                              then found="VestaCP"
    elif [ -d /usr/local/ispconfig ];                                          then found="ISPConfig"
    elif [ -d /usr/local/cwpsrv ];                                             then found="CentOS Web Panel"
    elif [ -d /etc/webmin/virtual-server ];                                    then found="Virtualmin"
    elif command -v clpctl >/dev/null 2>&1;                                    then found="CloudPanel"
    fi
    [ -z "$found" ] && return 0
    echo "[panel] detected $found" >> "$LOG"
    echo -e "\n${RED}${BOLD}✗ ${found} is installed on this server.${NC}"
    echo "   ${found} manages ports 80 and 443 for its own websites. Installing NgStack"
    echo "   here would take those websites offline and the two panels would conflict."
    echo "   Nothing was changed on this server."
    echo -e "   Use a server without another hosting panel. Guide: ${CYAN}https://ngstack.net/install#requirements${NC}"
    exit 1
}

preflight() {
    [ "$(id -u)" -eq 0 ] || fail "Run as root: sudo ./ngstack-installer"
    : > "$LOG"; chmod 600 "$LOG"
    echo "NgStack installer $INSTALLER_VERSION — $(date -u)" >> "$LOG"
    detect_hosting_panel

    # read os-release in a subshell: it defines generic names (VERSION, ID…) we must not import
    local os_id="" os_like="" os_name=""
    if [ -r /etc/os-release ]; then
        os_id=$(. /etc/os-release && echo "${ID:-}")
        os_like=$(. /etc/os-release && echo "${ID_LIKE:-}")
        os_name=$(. /etc/os-release && echo "${PRETTY_NAME:-}")
    fi
    case "$os_id $os_like" in
        *ubuntu*|*debian*) ok "Operating system: ${os_name:-$os_id}" ;;
        *) warn "Tested on Ubuntu and Debian. Detected: ${os_name:-unknown}"
           if has_tty; then yes_no ">> Continue anyway? (y/n) [n]: " n || fail "Installation cancelled."; fi ;;
    esac
    case "$(uname -m)" in x86_64|amd64) ;; *) fail "Unsupported CPU: $(uname -m). NgStack needs a 64-bit Intel/AMD (x86_64) server." ;; esac

    for bin in curl ss getent; do
        command -v "$bin" >/dev/null 2>&1 && continue
        if command -v apt-get >/dev/null 2>&1; then
            info "Installing $bin…"
            quiet env DEBIAN_FRONTEND=noninteractive apt-get update -qq || true
            quiet env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq curl iproute2 libc-bin ca-certificates || fail "Could not install $bin"
        else
            fail "Missing tool: $bin"
        fi
    done

    local mem_mb; mem_mb=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo)
    [ "$mem_mb" -ge 900 ] || warn "Only ${mem_mb} MB RAM. 1 GB or more is recommended."
    local free_gb; free_gb=$(df -BG --output=avail / | tail -n1 | tr -dc '0-9')
    [ "${free_gb:-0}" -ge 5 ] || fail "Only ${free_gb} GB free disk space. At least 5 GB is needed."
}

detect_cloud() {
    if curl -s -m 2 -X PUT http://169.254.169.254/latest/api/token -H "X-aws-ec2-metadata-token-ttl-seconds: 30" -o /dev/null -w '%{http_code}' 2>/dev/null | grep -q 200; then CLOUD="aws"
    elif curl -s -m 2 http://169.254.169.254/metadata/v1/id -o /dev/null -w '%{http_code}' 2>/dev/null | grep -q 200; then CLOUD="digitalocean"
    elif curl -s -m 2 -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/ -o /dev/null -w '%{http_code}' 2>/dev/null | grep -q 200; then CLOUD="gcp"
    elif curl -s -m 2 -H "Metadata: true" "http://169.254.169.254/metadata/instance?api-version=2021-02-01" -o /dev/null -w '%{http_code}' 2>/dev/null | grep -q 200; then CLOUD="azure"
    elif curl -s -m 2 http://169.254.169.254/hetzner/v1/metadata -o /dev/null -w '%{http_code}' 2>/dev/null | grep -q 200; then CLOUD="hetzner"
    fi
    SERVER_IP=$(curl -s -4 -m 5 https://checkip.amazonaws.com 2>/dev/null | tr -dc '0-9.' || true)
    [ -n "$SERVER_IP" ] || SERVER_IP=$(curl -s -4 -m 5 https://api.ipify.org 2>/dev/null | tr -dc '0-9.' || true)
    [[ "$SERVER_IP" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || fail "Could not detect this server's public IPv4 address."
    ok "Public IP: $SERVER_IP${CLOUD:+ (${CLOUD})}"
}

# ---------------------------------------------------------------------
# 2. Ports
# ---------------------------------------------------------------------
port_owner() { # prints "process" listening on TCP port $1, empty if free
    ss -Htlnp "sport = :$1" 2>/dev/null | sed -n 's/.*users:(("\([^"]*\)".*/\1/p' | head -n1
}
port_busy() { [ -n "$(ss -Htln "sport = :$1" 2>/dev/null)" ]; }

free_web_ports() {
    local p owner svc
    for p in 80 443; do
        port_busy "$p" || continue
        owner=$(port_owner "$p")
        # our own nginx from a previous install is fine — it is replaced below
        if docker ps --format '{{.Names}}' 2>/dev/null | grep -qx ngstack-nginx; then continue; fi
        svc=""
        case "$owner" in
            nginx*) svc=nginx ;; apache2*) svc=apache2 ;; httpd*) svc=httpd ;; caddy*) svc=caddy ;; lighttpd*) svc=lighttpd ;;
        esac
        if [ -n "$svc" ] && command -v systemctl >/dev/null 2>&1; then
            warn "Port $p is used by the system web server \"$svc\". NgStack needs ports 80/443 to serve your sites."
            if [ "${NGSTACK_FREE_PORTS:-}" = "1" ] || { has_tty && yes_no ">> Stop and disable $svc? (y/n) [y]: " y; }; then
                quiet systemctl stop "$svc" || true
                quiet systemctl disable "$svc" || true
                sleep 1
                port_busy "$p" && fail "Port $p is still busy after stopping $svc."
                ok "Stopped and disabled $svc"
            else
                fail "Port $p is busy ($svc). Free it and run the installer again."
            fi
        else
            local hint="${owner:-unknown process}"
            if [ "$owner" = "docker-proxy" ]; then
                hint="a Docker container ($(docker ps --filter "publish=$p" --format '{{.Names}}' | paste -sd, -))"
            fi
            fail "Port $p is already used by $hint. NgStack needs ports 80 and 443 for your sites. Stop it and run the installer again."
        fi
    done
    ok "Ports 80 and 443 are free for your sites"
}

pick_ports() {
    [[ "$PANEL_PORT" =~ ^[0-9]+$ ]] && [ "$PANEL_PORT" -ge 1024 ] && [ "$PANEL_PORT" -le 65535 ] || fail "NGSTACK_PANEL_PORT must be 1024-65535"
    local old_ui="" old_agent=""
    if docker ps -a --format '{{.Names}}' 2>/dev/null | grep -qx ngstack-panel; then
        # reinstall: keep the exact internal ports of the existing panel (they free up when it is replaced)
        old_ui=$(docker inspect -f '{{range $p, $b := .HostConfig.PortBindings}}{{if eq $p "3000/tcp"}}{{(index $b 0).HostPort}}{{end}}{{end}}' ngstack-panel 2>/dev/null || true)
        old_agent=$(docker inspect -f '{{range $p, $b := .HostConfig.PortBindings}}{{if eq $p "8080/tcp"}}{{(index $b 0).HostPort}}{{end}}{{end}}' ngstack-panel 2>/dev/null || true)
    fi
    if [[ "$old_ui" =~ ^[0-9]+$ ]] && [[ "$old_agent" =~ ^[0-9]+$ ]]; then
        UI_PORT="$old_ui"; AGENT_PORT="$old_agent"
    else
        while port_busy "$UI_PORT"; do UI_PORT=$((UI_PORT+1)); done
        while port_busy "$AGENT_PORT" || [ "$AGENT_PORT" = "$UI_PORT" ]; do AGENT_PORT=$((AGENT_PORT+1)); done
    fi
    # the panel port may already be held by our own gateway from a previous 2.0 install
    if ! docker ps --format '{{.Names}}' 2>/dev/null | grep -qx ngstack-nginx; then
        while port_busy "$PANEL_PORT"; do warn "Port $PANEL_PORT is busy, trying $((PANEL_PORT+1))"; PANEL_PORT=$((PANEL_PORT+1)); done
    fi
    ok "Panel port: $PANEL_PORT (HTTPS) · internal: $UI_PORT, $AGENT_PORT (localhost only)"
}

# ---------------------------------------------------------------------
# 3. Questions
# ---------------------------------------------------------------------
normalize_domain() { echo "$1" | tr '[:upper:]' '[:lower:]' | sed -e 's#^[a-z]*://##' -e 's#/.*$##' -e 's/^www\.//;s/\.$//' -e 's/[[:space:]]//g'; }
valid_domain() { [[ "$1" =~ ^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$ ]]; }
valid_email() { [[ "$1" =~ ^[^@[:space:]]+@[^@[:space:]]+\.[a-zA-Z]{2,}$ ]]; }

check_dns() { # 0 = points here, 1 = elsewhere, 2 = no record
    local ips; ips=$(getent ahostsv4 "$1" 2>/dev/null | awk '{print $1}' | sort -u || true)
    [ -z "$ips" ] && return 2
    echo "$ips" | grep -qx "$SERVER_IP" && return 0
    return 1
}

confirm_dns() {
    while :; do
        local st=0; check_dns "$DOMAIN" || st=$?
        if [ "$st" -eq 0 ]; then ok "$DOMAIN points to this server"; return 0; fi
        if [ "$st" -eq 1 ]; then
            warn "$DOMAIN points to $(getent ahostsv4 "$DOMAIN" | awk '{print $1}' | sort -u | paste -sd' ' -), not to this server ($SERVER_IP)."
        else
            warn "$DOMAIN has no DNS record yet."
        fi
        echo -e "   Add this record at your domain provider:\n   ${CYAN}Type: A    Name: ${DOMAIN}    Value: ${SERVER_IP}${NC}"
        if ! has_tty; then warn "Continuing; the SSL step will fail until DNS is correct."; return 0; fi
        echo "   1) Check again (DNS can take a few minutes)"
        echo "   2) Continue with this domain anyway"
        echo "   3) Install without a domain (use https://${SERVER_IP}:${PANEL_PORT})"
        local c; ask ">> Choose 1-3 [1]: " c
        case "${c:-1}" in
            2) return 0 ;;
            3) DOMAIN=""; EMAIL=""; return 0 ;;
            *) info "Checking again…"; sleep 5 ;;
        esac
    done
}

questions() {
    LICENSE_KEY="${NGSTACK_LICENSE:-}"
    ADMIN_USER="${NGSTACK_ADMIN_USER:-}"
    ADMIN_PASS="${NGSTACK_ADMIN_PASS:-}"
    [ -n "$LICENSE_KEY" ] || ask "🔑 NgStack license key: " LICENSE_KEY
    LICENSE_KEY=$(echo "$LICENSE_KEY" | tr -d '[:space:]')
    [[ "$LICENSE_KEY" =~ ^RX-[A-Za-z0-9-]{6,47}$ ]] || fail "That does not look like an NgStack license key (RX-…). Get one free at https://cust.ngstack.net"

    while [ -z "$ADMIN_USER" ]; do ask "👤 Admin username: " ADMIN_USER; ADMIN_USER=$(echo "$ADMIN_USER" | tr -d '[:space:]'); done
    [[ "$ADMIN_USER" =~ ^[A-Za-z0-9._@-]{3,64}$ ]] || fail "Username: 3-64 characters (letters, numbers, . _ @ -)"
    [ "${ADMIN_USER,,}" = "admin" ] && warn "\"admin\" is the first name attackers try. A unique username is safer."

    if [ -z "$ADMIN_PASS" ]; then
        local p2
        while :; do
            ask "🔒 Admin password (8+ characters): " ADMIN_PASS silent
            [ "${#ADMIN_PASS}" -ge 8 ] || { warn "At least 8 characters."; continue; }
            ask "🔒 Repeat the password: " p2 silent
            [ "$ADMIN_PASS" = "$p2" ] && break
            warn "Passwords do not match."
        done
    fi
    [ "${#ADMIN_PASS}" -ge 8 ] || fail "The admin password needs at least 8 characters."

    # domain for the panel (optional)
    if [ -n "${NGSTACK_DOMAIN:-}" ]; then
        DOMAIN=$(normalize_domain "$NGSTACK_DOMAIN"); EMAIL="${NGSTACK_EMAIL:-}"
        valid_domain "$DOMAIN" || fail "NGSTACK_DOMAIN is not a valid domain: $DOMAIN"
        valid_email "$EMAIL" || fail "NGSTACK_EMAIL must be a valid email when NGSTACK_DOMAIN is set."
    elif has_tty; then
        echo -e "\n${CYAN}${BOLD}Panel address and free SSL (HTTPS)${NC}"
        echo "  With a domain or subdomain (example: panel.mysite.com) the panel gets a"
        echo "  trusted certificate: https://panel.mysite.com"
        echo "  Without one it opens at https://${SERVER_IP}:${PANEL_PORT} (your browser will warn"
        echo "  once about the self-signed certificate — that is expected)."
        if yes_no ">> Do you have a domain for the panel? (y/n) [n]: " n; then
            while :; do
                local d; ask ">> Domain or subdomain (example: panel.mysite.com): " d
                d=$(normalize_domain "$d")
                valid_domain "$d" && { DOMAIN="$d"; break; }
                warn "That is not a valid domain. Try again."
            done
            while :; do
                ask ">> Email for SSL renewal notices: " EMAIL
                valid_email "$EMAIL" && break
                warn "Please enter a valid email address."
            done
        fi
    fi
    [ -n "$DOMAIN" ] && confirm_dns
    return 0
}

# ---------------------------------------------------------------------
# 4. License + Docker
# ---------------------------------------------------------------------
verify_license() {
    info "Verifying your license…"
    local body resp
    body=$(printf '{"license_key":"%s"}' "$LICENSE_KEY")
    resp=$(curl -s -m 20 -X POST "$LICENSE_API" -H "Content-Type: application/json" -d "$body" || true)
    if ! echo "$resp" | grep -q '"valid"[[:space:]]*:[[:space:]]*true'; then
        local code; code=$(echo "$resp" | sed -n 's/.*"code"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
        case "$code" in
            bound_elsewhere) fail "This license is bound to another server. Open https://cust.ngstack.net, press \"Unbind server\", then run the installer again." ;;
            expired)         fail "This license has expired. Renew it for free at https://cust.ngstack.net" ;;
            suspended)       fail "This license is suspended. Contact support at https://cust.ngstack.net" ;;
            "")              fail "Could not reach the license server or the key is not valid. Check the key and the server's internet connection." ;;
            *)               fail "License not accepted ($code). Get a valid key at https://cust.ngstack.net" ;;
        esac
    fi
    DOCKER_PAT=$(echo "$resp" | sed -n 's/.*"docker_pat"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
    [ -n "$DOCKER_PAT" ] || fail "The license server did not return a download token. Contact support."
    ok "License verified"
}

install_docker() {
    if command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then ok "Docker is ready ($(docker --version | awk '{print $3}' | tr -d ,))"; return; fi
    info "Installing Docker (a few minutes)…"
    curl -fsSL https://get.docker.com -o /tmp/get-docker.sh || fail "Could not download the Docker installer."
    quiet sh /tmp/get-docker.sh || fail "Docker installation failed."
    rm -f /tmp/get-docker.sh
    command -v systemctl >/dev/null 2>&1 && quiet systemctl enable --now docker || true
    docker info >/dev/null 2>&1 || fail "Docker is installed but not running."
    ok "Docker installed"
}

registry_login() {
    if [ "$TEST_MODE" = "1" ] && docker image inspect ngstack/panel:latest >/dev/null 2>&1; then
        warn "Test mode: using the local ngstack/panel image"; return
    fi
    echo "$DOCKER_PAT" | docker login -u ngstack --password-stdin >/dev/null 2>&1 || fail "Could not authenticate with the NgStack registry. Contact support."
    ok "Connected to the NgStack registry"
}

# ---------------------------------------------------------------------
# 5. Containers + nginx
# ---------------------------------------------------------------------
remove_old() {
    # park the current install (stopped + renamed) instead of deleting it: if anything below fails,
    # fail() puts it back; it is removed only after the new install answers
    local c
    for c in ngstack-updater ngstack-panel ngstack-nginx; do
        docker rm -f "${c}__prev" >/dev/null 2>&1 || true
        if docker ps -a --format '{{.Names}}' | grep -qx "$c"; then
            info "Replacing the existing $c (kept aside until the new one works; your data in /root is kept)"
            quiet docker stop "$c" || true
            quiet docker rename "$c" "${c}__prev" || fail "Could not set aside the existing $c."
            PREV_SAVED=1
        fi
    done
}

start_nginx() {
    info "Building the NgStack web gateway (nginx + certbot)…"
    local dir; dir=$(mktemp -d)
    printf 'FROM nginx:alpine\nRUN apk add --no-cache certbot certbot-nginx openssl\n' > "$dir/Dockerfile"
    quiet docker build -t ngstack/nginx-ssl "$dir" || fail "Building the web gateway failed."
    rm -rf "$dir"
    mkdir -p /etc/nginx/conf.d /etc/letsencrypt/ngstack-selfsigned
    chmod 755 /etc/nginx /etc/nginx/conf.d

    # self-signed certificate for https://IP:PORT (valid 10 years, regenerated only if missing)
    if [ ! -s /etc/letsencrypt/ngstack-selfsigned/panel.crt ]; then
        quiet docker run --rm -v /etc/letsencrypt/ngstack-selfsigned:/c --entrypoint openssl ngstack/nginx-ssl \
            req -x509 -nodes -newkey rsa:2048 -days 3650 -keyout /c/panel.key -out /c/panel.crt \
            -subj "/CN=NgStack Panel" -addext "subjectAltName=IP:${SERVER_IP}" || fail "Creating the panel certificate failed."
        chmod 600 /etc/letsencrypt/ngstack-selfsigned/panel.key
    fi

    write_gateway_conf
    quiet docker run -d --name ngstack-nginx --restart always --network host \
        -v /etc/nginx/conf.d:/etc/nginx/conf.d -v /etc/letsencrypt:/etc/letsencrypt \
        ngstack/nginx-ssl || fail "Starting the web gateway failed."
    sleep 2
    docker ps --format '{{.Names}}' | grep -qx ngstack-nginx || { docker logs --tail 15 ngstack-nginx >&2 || true; fail "The web gateway stopped right after starting."; }
    docker exec ngstack-nginx nginx -t >/dev/null 2>&1 || fail "nginx configuration test failed."
    ok "Web gateway running on ports 80, 443 and $PANEL_PORT"
}

panel_locations() {
    cat <<EOF
    client_max_body_size 500m;
    proxy_read_timeout 3600s;
    location /api/ {
        proxy_pass http://127.0.0.1:${AGENT_PORT}/api/;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
    }
    location / {
        proxy_pass http://127.0.0.1:${UI_PORT};
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
    }
EOF
}

write_gateway_conf() {
    # default server: unknown hosts get nothing; the bare IP is sent to the panel port
    cat > /etc/nginx/conf.d/default.conf <<EOF
# NgStack — default server (managed by the installer)
server {
    listen 80 default_server;
    server_name _;
    location /.well-known/acme-challenge/ { root /usr/share/nginx/html; }
    location / {
        if (\$host = "${SERVER_IP}") { return 301 https://${SERVER_IP}:${PANEL_PORT}/; }
        return 404;
    }
}
EOF
    # the panel on its own port, HTTPS only
    {
        echo "# NgStack panel (managed by the installer)"
        echo "server {"
        echo "    listen ${PANEL_PORT} ssl default_server;"
        echo "    http2 on;"
        echo "    server_name _;"
        echo "    ssl_certificate     /etc/letsencrypt/ngstack-selfsigned/panel.crt;"
        echo "    ssl_certificate_key /etc/letsencrypt/ngstack-selfsigned/panel.key;"
        echo "    ssl_protocols TLSv1.2 TLSv1.3;"
        echo "    # plain http://IP:${PANEL_PORT} → https"
        echo "    error_page 497 =301 https://\$host:\$server_port\$request_uri;"
        panel_locations
        echo "}"
    } > /etc/nginx/conf.d/00-ngstack-panel.conf
}

# AWS / Google Cloud / Azure block every port except 22 by default, so Let's
# Encrypt cannot reach port 80 until the admin opens it. Pause once, before the
# certificate request, so the certificate works on the first try.
cloud_ports_gate() {
    [ -n "$DOMAIN" ] || return 0
    local where=""
    case "$CLOUD" in
        aws)   where="AWS Console → EC2 → Instances → your server → Security → Security groups → Edit inbound rules" ;;
        gcp)   where="Google Cloud → VPC network → Firewall → Create firewall rule" ;;
        azure) where="Azure → your VM → Networking → Add inbound port rule" ;;
        *)     return 0 ;;
    esac
    echo -e "\n${YELLOW}${BOLD}🔥 Action needed before the SSL certificate:${NC}"
    echo -e "   Your server is on ${BOLD}${CLOUD^^}${NC}, which blocks incoming traffic by default."
    echo -e "   Open these ports (Inbound, TCP, source 0.0.0.0/0):"
    echo -e "   ${BOLD}80${NC}     → required now, to verify ${DOMAIN}"
    echo -e "   ${BOLD}443${NC}    → your websites (HTTPS)"
    echo -e "   ${BOLD}${PANEL_PORT}${NC}  → NgStack panel"
    echo -e "   Where: ${CYAN}${where}${NC}"
    echo -e "   Step-by-step guide: ${CYAN}https://ngstack.net/install#${CLOUD}${NC}"
    if [ "${NGSTACK_PORTS_READY:-0}" = "1" ] || ! has_tty; then
        info "Continuing without waiting (unattended install)."
        return 0
    fi
    local _r
    ask "   Press Enter once the ports are open… " _r
}

panel_domain_ssl() {
    [ -n "$DOMAIN" ] || return 0
    info "Requesting a free SSL certificate for $DOMAIN…"
    # temporary HTTP server for the domain so Let's Encrypt can verify it
    cat > /etc/nginx/conf.d/00-ngstack-panel-domain.conf <<EOF
# NgStack panel domain (managed by the installer)
server {
    listen 80;
    server_name ${DOMAIN};
    location /.well-known/acme-challenge/ { root /usr/share/nginx/html; }
    location / { return 301 https://\$host\$request_uri; }
}
EOF
    docker exec ngstack-nginx nginx -s reload >/dev/null 2>&1 || true
    if quiet docker exec ngstack-nginx certbot certonly --webroot -w /usr/share/nginx/html -d "$DOMAIN" \
            --non-interactive --agree-tos -m "$EMAIL" --keep-until-expiring; then
        cat >> /etc/nginx/conf.d/00-ngstack-panel-domain.conf <<EOF
server {
    listen 443 ssl;
    http2 on;
    server_name ${DOMAIN};
    ssl_certificate     /etc/letsencrypt/live/${DOMAIN}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    add_header Strict-Transport-Security "max-age=31536000" always;
$(panel_locations)
}
EOF
        docker exec ngstack-nginx nginx -t >/dev/null 2>&1 && docker exec ngstack-nginx nginx -s reload >/dev/null 2>&1
        SSL_MODE="letsencrypt"
        ok "SSL certificate issued for $DOMAIN"
    else
        warn "Could not get a certificate for $DOMAIN (DNS not ready or port 80 blocked by a firewall)."
        warn "The panel still works at https://${SERVER_IP}:${PANEL_PORT}. Add the domain later from Domains & SSL."
        rm -f /etc/nginx/conf.d/00-ngstack-panel-domain.conf
        docker exec ngstack-nginx nginx -s reload >/dev/null 2>&1 || true
    fi
}

start_panel() {
    info "Downloading and starting the NgStack panel…"
    if [ "$TEST_MODE" != "1" ]; then quiet docker pull ngstack/panel:latest || fail "Downloading the panel failed."; fi
    local env_args=(-e NGSTACK_LICENSE="$LICENSE_KEY")
    [ "$TEST_MODE" = "1" ] && env_args+=(-e LICENSE_SERVER_URL="$LICENSE_API")
    # no admin password in the environment: it is set through the panel's setup API below (stored hashed)
    quiet docker run -d --name ngstack-panel --restart always \
        -p "127.0.0.1:${UI_PORT}:3000" -p "127.0.0.1:${AGENT_PORT}:8080" \
        -v /var/run/docker.sock:/var/run/docker.sock -v /root:/root \
        -v /etc/nginx/conf.d:/etc/nginx/conf.d -v /etc/letsencrypt:/etc/letsencrypt \
        "${env_args[@]}" ngstack/panel:latest || fail "Starting the panel failed."

    info "Waiting for the panel to start…"
    local status=""
    for _ in $(seq 1 60); do
        status=$(curl -sk -m 3 "https://127.0.0.1:${PANEL_PORT}/api/system/status" 2>/dev/null || true)
        echo "$status" | grep -q '"needs_activation"' && break
        # a container that already exited will never answer: stop waiting
        if [ -z "$(docker ps -q --filter name=^ngstack-panel$ --filter status=running)" ]; then
            docker logs --tail 20 ngstack-panel >&2 || true
            fail "The panel stopped right after starting."
        fi
        sleep 2
    done
    echo "$status" | grep -q '"needs_activation"' || { docker logs --tail 20 ngstack-panel >&2 || true; fail "The panel did not start within 2 minutes."; }
    echo "$status" | grep -q '"needs_activation":false' || fail "The panel could not activate the license (check the server's internet access)."
    ok "Panel is running"
}

create_admin() {
    local status; status=$(curl -sk -m 5 "https://127.0.0.1:${PANEL_PORT}/api/system/status" || true)
    if echo "$status" | grep -q '"needs_setup":false'; then
        warn "An admin account already exists from a previous install — it was kept. Log in with your existing password."
        return
    fi
    local body code
    # JSON-escape the password (backslash and quote) without ever writing it to disk or logs
    local esc_pass=${ADMIN_PASS//\\/\\\\}; esc_pass=${esc_pass//\"/\\\"}
    body=$(printf '{"license_key":"%s","username":"%s","password":"%s"}' "$LICENSE_KEY" "$ADMIN_USER" "$esc_pass")
    code=$(curl -sk -m 15 -o /tmp/ngstack-setup.out -w '%{http_code}' -X POST "https://127.0.0.1:${PANEL_PORT}/api/auth/setup" \
        -H "Content-Type: application/json" -H "X-NgStack-Lang: en" --data-binary @- <<< "$body" || true)
    unset body esc_pass
    if [ "$code" != "200" ]; then
        echo "setup answered $code: $(cat /tmp/ngstack-setup.out 2>/dev/null)" >> "$LOG"
        rm -f /tmp/ngstack-setup.out
        fail "Creating the admin account failed ($code). Open the panel to finish setup there."
    fi
    rm -f /tmp/ngstack-setup.out
    ok "Admin account \"$ADMIN_USER\" created (password stored hashed)"
}

start_updater() {
    quiet docker run -d --name ngstack-updater --restart always \
        -e DOCKER_API_VERSION=1.44 -e REPO_USER=ngstack -e REPO_PASS="$DOCKER_PAT" \
        -v /var/run/docker.sock:/var/run/docker.sock \
        containrrr/watchtower --cleanup --interval 86400 ngstack-panel || fail "Starting the auto-updater failed."
    ok "Automatic updates enabled (checked every 24 hours)"
}

# ---------------------------------------------------------------------
# 6. Firewall
# ---------------------------------------------------------------------
open_local_firewall() {
    local p
    if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q "Status: active"; then
        for p in 80 443 "$PANEL_PORT"; do quiet ufw allow "${p}/tcp" || true; done
        ok "Opened 80, 443, $PANEL_PORT in ufw"
    fi
    if command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then
        for p in 80 443 "$PANEL_PORT"; do quiet firewall-cmd --permanent --add-port="${p}/tcp" || true; done
        quiet firewall-cmd --reload || true
        ok "Opened 80, 443, $PANEL_PORT in firewalld"
    fi
}

cloud_firewall_note() {
    local where=""
    case "$CLOUD" in
        aws)          where="AWS Console → EC2 → Instances → your server → Security → Security groups → Edit inbound rules" ;;
        digitalocean) where="DigitalOcean → Networking → Firewalls (if you use one)" ;;
        gcp)          where="Google Cloud → VPC network → Firewall" ;;
        azure)        where="Azure → your VM → Networking → Inbound port rules" ;;
        hetzner)      where="Hetzner Console → Firewalls (if you use one)" ;;
    esac
    echo -e "\n${YELLOW}${BOLD}🔥 Firewall:${NC} make sure these ports are open (Inbound, TCP, from anywhere):"
    echo -e "   ${BOLD}${PANEL_PORT}${NC}  → NgStack panel"
    echo -e "   ${BOLD}80, 443${NC} → your websites and SSL certificates"
    [ -n "$where" ] && echo -e "   Where: ${CYAN}${where}${NC}"
    echo "   Ports ${UI_PORT} and ${AGENT_PORT} are internal (localhost only) — never open them."
    echo -e "   Step-by-step guide: ${CYAN}https://ngstack.net/install${CLOUD:+#${CLOUD}}${NC}"
}

# ---------------------------------------------------------------------
main() {
    banner
    preflight
    detect_cloud
    questions
    verify_license
    install_docker
    free_web_ports
    pick_ports
    registry_login
    remove_old
    start_nginx
    cloud_ports_gate
    panel_domain_ssl
    start_panel
    create_admin
    start_updater
    open_local_firewall
    if [ "$PREV_SAVED" = "1" ]; then
        local c
        for c in ngstack-updater ngstack-panel ngstack-nginx; do docker rm -f "${c}__prev" >/dev/null 2>&1 || true; done
        PREV_SAVED=0
    fi
    unset ADMIN_PASS DOCKER_PAT

    local url="https://${SERVER_IP}:${PANEL_PORT}"
    [ "$SSL_MODE" = "letsencrypt" ] && url="https://${DOMAIN}"
    echo -e "\n${BLUE}=======================================================${NC}"
    echo -e "${GREEN}${BOLD}🎉 NgStack is installed and running${NC}"
    echo -e "🌍 Panel:  ${BOLD}${url}${NC}"
    [ "$SSL_MODE" = "letsencrypt" ] && echo -e "   Also:   https://${SERVER_IP}:${PANEL_PORT}"
    [ "$SSL_MODE" != "letsencrypt" ] && echo -e "   ${YELLOW}Your browser will warn about the certificate the first time — choose \"Advanced → Proceed\".${NC}"
    echo -e "👤 Admin:  ${ADMIN_USER}"
    echo -e "🛡️  First step after login: Settings → Security → enable two-factor authentication."
    cloud_firewall_note
    echo -e "${BLUE}=======================================================${NC}"
    echo "[done] installed $(date -u)" >> "$LOG"
}

main "$@"
