#!/usr/bin/env bash
# install_nocos.sh — Instalador 1-linha do NocOS (install.nocos.com.br) para Debian 12/13 (amd64).
#
# Modos de uso:
#   1) Modo unclaimed (instala pronto para reivindicação posterior; prompt opcional de e-mail):
#      curl -fsSL https://install.nocos.com.br | sudo bash
#
#   2) Modo com token efêmero pré-emitido (Trial ou Produção):
#      curl -fsSL https://install.nocos.com.br | sudo bash -s -- --token bt_xxx.secret
#
#   3) Modo unclaimed não-interativo com envio de código de ativação por e-mail:
#      curl -fsSL https://install.nocos.com.br | sudo bash -s -- --unclaimed --email ops@provedor.com.br
#
# Variáveis opcionais de ambiente:
#   NOCOS_TOKEN / NOCWORK_BOOTSTRAP_TOKEN   Token de bootstrap (--token)
#   NOCOS_API_URL                           Base da API Master (padrão: https://api.nocos.com.br)
#   NOCOS_INSTALL_URL                       Base do instalador (padrão: https://install.nocos.com.br)
#   NOCOS_TARBALL                           Caminho local de tarball .tar.gz
#   NOCOS_TARBALL_URL                       URL direta do tarball .tar.gz
#   NOCOS_TARBALL_SHA256                    Checksum SHA-256 esperado (64 hex)
#   NOCOS_EMAIL                             E-mail opcional para envio de código de ativação
#   NOCOS_NON_INTERACTIVE=1                 Desabilita prompts interativos
#   NOCOS_LISTEN_IP                         IP de bind do painel (:9090)
#   NOCOS_HTTPS_PORT                        Porta HTTPS local (padrão: 9443)

set -euo pipefail
IFS=$'\n\t'
export PATH="/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:${PATH:-}"

_nocos_die()  { printf '\033[1;31m[ERRO]\033[0m %s\n' "$*" >&2; exit 1; }
_nocos_info() { printf '\033[1;36m[..]\033[0m %s\n' "$*"; }
_nocos_ok()   { printf '\033[1;32m[OK]\033[0m %s\n' "$*"; }
_nocos_warn() { printf '\033[1;33m[!!]\033[0m %s\n' "$*" >&2; }

NOCOS_TOKEN="${NOCOS_TOKEN:-${NOCWORK_BOOTSTRAP_TOKEN:-}}"
NOCOS_MODE=""
NOCOS_API_URL="${NOCOS_API_URL:-https://api.nocos.com.br}"
NOCOS_INSTALL_URL="${NOCOS_INSTALL_URL:-https://install.nocos.com.br}"
NOCOS_TARBALL_PATH="${NOCOS_TARBALL:-${NOCWORK_INSTALLER_TARBALL:-}}"
NOCOS_TARBALL_URL="${NOCOS_TARBALL_URL:-${NOCWORK_INSTALLER_URL:-}}"
NOCOS_TARBALL_SHA256="${NOCOS_TARBALL_SHA256:-${NOCWORK_INSTALLER_SHA256:-}}"
NOCOS_EMAIL="${NOCOS_EMAIL:-}"
NOCOS_NON_INTERACTIVE="${NOCOS_NON_INTERACTIVE:-0}"
NOCOS_NO_EMAIL=0
NOCOS_ALLOW_UNVERIFIED=0
NOCOS_LISTEN_IP="${NOCOS_LISTEN_IP:-${NOCWORK_LISTEN_IP:-}}"
NOCOS_HTTPS_PORT="${NOCOS_HTTPS_PORT:-9443}"
NOCOS_REDIRECT_HTTPS="${NOCOS_REDIRECT_HTTPS:-1}"

NOCOS_HWID=""
NOCOS_HOST=""
NOCOS_LIC_ID=""
NOCOS_LIC_CNPJ=""
NOCOS_LIC_SECRET=""
NOCOS_TLS_DOMAIN=""
NOCOS_IS_TRIAL="false"
NOCOS_EXPIRES_AT=""
NOCOS_CLAIM_CODE=""
NOCOS_CLAIM_URL=""

_nocos_usage() {
    cat <<'EOF'
Uso: sudo bash install_nocos.sh [opções]

Opções:
  --token <TOKEN>        Instala e vincula usando token efêmero do License Master
  --unclaimed            Instala em modo unclaimed (padrão quando --token não é informado)
  --email <EMAIL>        E-mail para envio do código de ativação (modo unclaimed)
  --no-email             Não solicita e-mail interativamente no modo unclaimed
  --non-interactive, -y  Executa sem prompts interativos
  --api-url <URL>        URL base da API Master (padrão: https://api.nocos.com.br)
  --install-url <URL>    URL base do repositório de instalação (padrão: https://install.nocos.com.br)
  --tarball <ARQUIVO>    Usa pacote .tar.gz local em vez de baixar via HTTPS
  --installer-url <URL>  URL explícita do tarball do instalador
  --sha256 <HEX>         Checksum SHA-256 esperado do tarball (64 hex)
  --allow-unverified     Permite tarball sem SHA-256 (uso apenas em lab offline)
  --listen-ip <IP>       Restringe o bind HTTP do painel ao IP informado
  --https-port <PORTA>   Porta HTTPS do painel (padrão: 9443)
  --no-redirect          Não redireciona HTTP -> HTTPS automaticamente
  -h, --help             Exibe esta ajuda
EOF
}

_nocos_parse_args() {
    while [ $# -gt 0 ]; do
        case "$1" in
            --token)
                [ $# -ge 2 ] || _nocos_die "Parâmetro --token requer um valor."
                NOCOS_TOKEN="${2}"
                NOCOS_MODE="token"
                shift 2
                ;;
            --unclaimed)
                NOCOS_MODE="unclaimed"
                shift
                ;;
            --email)
                [ $# -ge 2 ] || _nocos_die "Parâmetro --email requer um endereço."
                NOCOS_EMAIL="${2}"
                shift 2
                ;;
            --no-email)
                NOCOS_NO_EMAIL=1
                shift
                ;;
            --non-interactive|-y|--yes)
                NOCOS_NON_INTERACTIVE=1
                shift
                ;;
            --api-url|--master-url)
                [ $# -ge 2 ] || _nocos_die "Parâmetro $1 requer uma URL."
                NOCOS_API_URL="${2%/}"
                shift 2
                ;;
            --install-url)
                [ $# -ge 2 ] || _nocos_die "Parâmetro --install-url requer uma URL."
                NOCOS_INSTALL_URL="${2%/}"
                shift 2
                ;;
            --tarball)
                [ $# -ge 2 ] || _nocos_die "Parâmetro --tarball requer um caminho."
                NOCOS_TARBALL_PATH="${2}"
                shift 2
                ;;
            --installer-url|--tarball-url)
                [ $# -ge 2 ] || _nocos_die "Parâmetro $1 requer uma URL."
                NOCOS_TARBALL_URL="${2}"
                shift 2
                ;;
            --sha256)
                [ $# -ge 2 ] || _nocos_die "Parâmetro --sha256 requer um digest SHA-256."
                NOCOS_TARBALL_SHA256="${2}"
                shift 2
                ;;
            --allow-unverified)
                NOCOS_ALLOW_UNVERIFIED=1
                shift
                ;;
            --listen-ip)
                [ $# -ge 2 ] || _nocos_die "Parâmetro --listen-ip requer um IP."
                NOCOS_LISTEN_IP="${2}"
                shift 2
                ;;
            --https-port)
                [ $# -ge 2 ] || _nocos_die "Parâmetro --https-port requer uma porta."
                NOCOS_HTTPS_PORT="${2}"
                shift 2
                ;;
            --no-redirect)
                NOCOS_REDIRECT_HTTPS=0
                shift
                ;;
            -h|--help)
                _nocos_usage
                exit 0
                ;;
            *)
                _nocos_die "Parâmetro desconhecido: $1 (use --help)."
                ;;
        esac
    done

    if [ -z "$NOCOS_MODE" ]; then
        if [ -n "$NOCOS_TOKEN" ]; then
            NOCOS_MODE="token"
        else
            NOCOS_MODE="unclaimed"
        fi
    fi

    if [ "$NOCOS_MODE" = "token" ] && [ -z "$NOCOS_TOKEN" ]; then
        _nocos_die "Modo --token exige o valor do token."
    fi
}

_nocos_valid_sha256() {
    local hex
    hex=$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]')
    [[ "$hex" =~ ^[0-9a-f]{64}$ ]]
}

_nocos_valid_email() {
    local em="${1:-}"
    [[ "$em" =~ ^[^@[:space:]]+@[^@[:space:]]+\.[^@[:space:]]+$ ]]
}

_nocos_preflight() {
    [ "$(id -u)" = "0" ] || _nocos_die "Execute como root (ex.: curl -fsSL https://install.nocos.com.br | sudo bash)."
    [ -f /etc/os-release ] || _nocos_die "Arquivo /etc/os-release ausente — sistema requer Debian 12 ou 13."

    local os_id="" ver_id="" arch=""
    # shellcheck disable=SC1091
    os_id=$(. /etc/os-release && printf '%s' "${ID:-}")
    # shellcheck disable=SC1091
    ver_id=$(. /etc/os-release && printf '%s' "${VERSION_ID:-}")
    [ "$os_id" = "debian" ] || _nocos_die "Distribuição '$os_id' não suportada. Homologado exclusivamente para Debian 12 (Bookworm) e Debian 13 (Trixie)."
    case "$ver_id" in
        12|13) ;;
        *)
            if [ -f /etc/debian_version ] && grep -Eq '^(12\.|13\.|bookworm|trixie)' /etc/debian_version; then
                :
            else
                _nocos_die "Debian versão '$ver_id' não suportada. Requer Debian 12 ou 13."
            fi
            ;;
    esac

    arch=$(dpkg --print-architecture 2>/dev/null || uname -m)
    case "$arch" in
        amd64|x86_64) ;;
        *) _nocos_die "Arquitetura '$arch' não suportada (requer amd64/x86_64)." ;;
    esac

    local need_apt=0
    for bin in curl jq openssl tar gzip sha256sum; do
        command -v "$bin" >/dev/null 2>&1 || need_apt=1
    done
    [ -f /etc/ssl/certs/ca-certificates.crt ] || need_apt=1

    if [ "$need_apt" = "1" ]; then
        _nocos_info "Instalando utilitários base (curl, jq, ca-certificates, openssl, tar, gzip)..."
        export DEBIAN_FRONTEND=noninteractive
        apt-get update -qq </dev/null >/dev/null 2>&1 || _nocos_die "Falha ao atualizar índices apt."
        apt-get install -y -qq curl jq ca-certificates openssl tar gzip coreutils </dev/null >/dev/null 2>&1 || _nocos_die "Falha ao instalar dependências base."
    fi

    if [ -n "$NOCOS_EMAIL" ] && ! _nocos_valid_email "$NOCOS_EMAIL"; then
        _nocos_die "E-mail inválido: $NOCOS_EMAIL"
    fi

    if [ -n "$NOCOS_TARBALL_SHA256" ] && ! _nocos_valid_sha256 "$NOCOS_TARBALL_SHA256"; then
        _nocos_die "Checksum --sha256 inválido (esperado 64 dígitos hexadecimais)."
    fi

    _nocos_ok "Ambiente Debian $ver_id ($arch) validado."
}

_nocos_compute_hwid() {
    local mid=""
    if [ -s /etc/machine-id ]; then
        mid=$(tr -d ' \t\r\n' < /etc/machine-id)
    elif [ -s /var/lib/dbus/machine-id ]; then
        mid=$(tr -d ' \t\r\n' < /var/lib/dbus/machine-id)
    else
        mid=$(hostname -f 2>/dev/null || hostname)
    fi
    NOCOS_HWID=$(printf 'nocwork-hwid-v1:%s' "$mid" | sha256sum | awk '{print substr($1,1,32)}')
    NOCOS_HOST=$(hostname 2>/dev/null || echo "nocos-node")
}

_nocos_claim_token() {
    local claim_url req_json resp http_code body err_msg
    claim_url="${NOCOS_API_URL%/}/v1/bootstrap/${NOCOS_TOKEN}/claim"
    req_json=$(jq -cn --arg m "$NOCOS_HWID" --arg h "$NOCOS_HOST" '{machine_id:$m, hostname:$h}')

    _nocos_info "Autenticando token e provisionando identidade TLS no Master..."
    resp=$(curl -sS -w "\n%{http_code}" --max-time 25 \
        -H "Content-Type: application/json" \
        -X POST "$claim_url" \
        -d "$req_json" 2>/dev/null || true)
    http_code=$(printf '%s' "$resp" | tail -n 1)
    body=$(printf '%s' "$resp" | sed '$d')

    if [ "$http_code" != "200" ]; then
        err_msg=$(printf '%s' "$body" | jq -r '.error // "token inválido, expirado ou já utilizado"' 2>/dev/null || echo "HTTP ${http_code:-erro}")
        _nocos_die "Resgate de token recusado pelo Master: $err_msg"
    fi

    NOCOS_LIC_ID=$(printf '%s' "$body" | jq -r '.license_id // empty')
    NOCOS_LIC_CNPJ=$(printf '%s' "$body" | jq -r '.license_cnpj // empty')
    NOCOS_LIC_SECRET=$(printf '%s' "$body" | jq -r '.license_secret // empty')
    NOCOS_TLS_DOMAIN=$(printf '%s' "$body" | jq -r '.tls_domain // empty')
    NOCOS_HTTPS_PORT=$(printf '%s' "$body" | jq -r --arg d "$NOCOS_HTTPS_PORT" '.https_port // $d')
    NOCOS_IS_TRIAL=$(printf '%s' "$body" | jq -r '.is_trial // false')
    NOCOS_EXPIRES_AT=$(printf '%s' "$body" | jq -r '.expires_at // empty')

    if [ -z "$NOCOS_TARBALL_URL" ]; then
        NOCOS_TARBALL_URL=$(printf '%s' "$body" | jq -r '.installer_url // empty')
    fi
    if [ -z "$NOCOS_TARBALL_SHA256" ]; then
        NOCOS_TARBALL_SHA256=$(printf '%s' "$body" | jq -r '.installer_sha256 // empty')
    fi

    [ -n "$NOCOS_LIC_ID" ] && [ -n "$NOCOS_LIC_SECRET" ] || _nocos_die "Resposta incompleta do Master no claim."
    _nocos_ok "Licença provisionada: $NOCOS_LIC_ID (${NOCOS_TLS_DOMAIN:-HTTPS habilitado})"
}

_nocos_prompt_optional_email() {
    [ "$NOCOS_MODE" = "unclaimed" ] || return 0
    [ -z "$NOCOS_EMAIL" ] || return 0
    [ "$NOCOS_NO_EMAIL" = "0" ] || return 0
    [ "$NOCOS_NON_INTERACTIVE" = "0" ] || return 0

    # Em execução via `curl ... | sudo bash`, stdin é o pipe; lê de /dev/tty se houver terminal.
    if [ ! -r /dev/tty ] || [ ! -w /dev/tty ]; then
        return 0
    fi

    echo
    printf 'Modo unclaimed selecionado: o NocOS será instalado sem licença pré-vinculada.\n' > /dev/tty
    printf 'Informe seu e-mail para receber o código de ativação (opcional; Enter para pular): ' > /dev/tty
    local entered=""
    if IFS= read -r entered < /dev/tty; then
        entered=$(printf '%s' "$entered" | tr -d '\r' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        if [ -n "$entered" ]; then
            if _nocos_valid_email "$entered"; then
                NOCOS_EMAIL="$entered"
            else
                _nocos_warn "E-mail '$entered' inválido — seguindo sem envio de código (ative depois pelo painel)."
            fi
        fi
    fi
}

_nocos_resolve_release_metadata() {
    # Se já temos tarball local + sha256 (ou allow-unverified), ou URL+sha256 completos, nada a consultar.
    if [ -n "$NOCOS_TARBALL_PATH" ]; then
        return 0
    fi
    if [ -n "$NOCOS_TARBALL_URL" ] && [ -n "$NOCOS_TARBALL_SHA256" ]; then
        return 0
    fi

    # 1. Tenta manifesto JSON em install.nocos.com.br/releases/latest.json
    local manifest_url="${NOCOS_INSTALL_URL%/}/releases/latest.json"
    local manifest=""
    manifest=$(curl -fsSL --max-time 15 "$manifest_url" 2>/dev/null || true)
    if [ -n "$manifest" ]; then
        if [ -z "$NOCOS_TARBALL_URL" ]; then
            NOCOS_TARBALL_URL=$(printf '%s' "$manifest" | jq -r '.installer_url // .url // empty' 2>/dev/null || true)
        fi
        if [ -z "$NOCOS_TARBALL_SHA256" ]; then
            NOCOS_TARBALL_SHA256=$(printf '%s' "$manifest" | jq -r '.installer_sha256 // .sha256 // empty' 2>/dev/null || true)
        fi
    fi

    # 2. Fallback padrão de URL caso o manifesto não informe
    if [ -z "$NOCOS_TARBALL_URL" ]; then
        NOCOS_TARBALL_URL="${NOCOS_INSTALL_URL%/}/nocos-installer.tar.gz"
    fi

    # 3. Se SHA-256 ainda ausente, busca sidecar <tarball_url>.sha256 ou SHA256SUMS (fail-closed)
    if [ -z "$NOCOS_TARBALL_SHA256" ]; then
        local sha_line=""
        sha_line=$(curl -fsSL --max-time 15 "${NOCOS_TARBALL_URL}.sha256" 2>/dev/null || true)
        if [ -n "$sha_line" ]; then
            NOCOS_TARBALL_SHA256=$(printf '%s' "$sha_line" | awk 'NR==1 {print tolower($1)}')
        fi
    fi
    if [ -z "$NOCOS_TARBALL_SHA256" ]; then
        local base_name sums=""
        base_name=$(basename "$NOCOS_TARBALL_URL")
        sums=$(curl -fsSL --max-time 15 "${NOCOS_INSTALL_URL%/}/SHA256SUMS" 2>/dev/null || true)
        if [ -n "$sums" ]; then
            NOCOS_TARBALL_SHA256=$(printf '%s\n' "$sums" | awk -v f="$base_name" '$2==f || $2==("./"f) {print tolower($1); exit}')
        fi
    fi
}

_nocos_verify_tarball_sha256() {
    local file="$1"
    [ -f "$file" ] || _nocos_die "Tarball não encontrado: $file"

    local got_sha
    got_sha=$(sha256sum "$file" | awk '{print tolower($1)}')

    if [ -z "$NOCOS_TARBALL_SHA256" ]; then
        if [ "$NOCOS_ALLOW_UNVERIFIED" = "1" ]; then
            _nocos_warn "SHA-256 omitido por --allow-unverified (digest observado: $got_sha)."
            return 0
        fi
        _nocos_die "Verificação SHA-256 obrigatória falhou: checksum esperado ausente para $file (use --sha256 ou publique .sha256/latest.json)."
    fi

    local exp_sha
    exp_sha=$(printf '%s' "$NOCOS_TARBALL_SHA256" | tr '[:upper:]' '[:lower:]')
    _nocos_valid_sha256 "$exp_sha" || _nocos_die "Checksum SHA-256 esperado malformado: $NOCOS_TARBALL_SHA256"

    if [ "$got_sha" != "$exp_sha" ]; then
        _nocos_die "Integridade SHA-256 recusada! Esperado=$exp_sha Obtido=$got_sha"
    fi
    _nocos_ok "Integridade SHA-256 confirmada ($got_sha)."
}

_nocos_run_install() {
    local stage_dir=""
    trap '[ -n "${stage_dir:-}" ] && rm -rf "$stage_dir" 2>/dev/null || true' EXIT

    local inst_script=""
    if [ -z "$NOCOS_TARBALL_PATH" ] && [ -z "$NOCOS_TARBALL_URL" ] && [ -f "./install.sh" ] && [ -d "./payload" ]; then
        inst_script="./install.sh"
        _nocos_info "Executando instalador a partir do diretório local atual."
    else
        stage_dir=$(mktemp -d /var/tmp/nw-stage-nocos.XXXXXXXX)
        chmod 0700 "$stage_dir"

        local tb="$NOCOS_TARBALL_PATH"
        if [ -n "$tb" ] && [ -z "$NOCOS_TARBALL_SHA256" ] && [ -f "${tb}.sha256" ]; then
            NOCOS_TARBALL_SHA256=$(awk 'NR==1 {print tolower($1)}' "${tb}.sha256")
        fi
        if [ -z "$tb" ]; then
            _nocos_resolve_release_metadata
            tb="$stage_dir/nocos-installer.tar.gz"
            _nocos_info "Baixando pacote NocOS de $NOCOS_TARBALL_URL..."
            curl -fsSL --max-time 300 -o "$tb" "$NOCOS_TARBALL_URL" || _nocos_die "Falha ao baixar tarball de $NOCOS_TARBALL_URL."
        fi

        _nocos_verify_tarball_sha256 "$tb"

        tar -xzf "$tb" -C "$stage_dir" || _nocos_die "Falha ao extrair tarball $tb."
        if [ -f "$stage_dir/install.sh" ]; then
            inst_script="$stage_dir/install.sh"
        elif [ -f "$stage_dir/installer/install.sh" ]; then
            inst_script="$stage_dir/installer/install.sh"
        else
            _nocos_die "install.sh não encontrado dentro do tarball."
        fi
    fi

    local mode_flag="--install"
    if [ -x /usr/local/sbin/nocwork ] && [ -f /etc/nocwork/.installed ]; then
        mode_flag="--upgrade"
        _nocos_info "Instalação prévia detectada — aplicando convergência (--upgrade)."
    fi

    local extra_args=("$mode_flag" "--non-interactive" "--enable-https" "--https-port" "${NOCOS_HTTPS_PORT:-9443}")
    [ -n "${NOCOS_TLS_DOMAIN:-}" ] && extra_args+=("--https-domain" "$NOCOS_TLS_DOMAIN")
    [ "${NOCOS_REDIRECT_HTTPS:-1}" = "1" ] && extra_args+=("--redirect-https")
    [ -n "${NOCOS_LISTEN_IP:-}" ] && extra_args+=("--listen-ip" "$NOCOS_LISTEN_IP")

    if [ "$NOCOS_MODE" = "token" ]; then
        NOCWORK_LICENSE_MASTER_URL="$NOCOS_API_URL" \
        NOCWORK_LICENSE_ID="$NOCOS_LIC_ID" \
        NOCWORK_LICENSE_CNPJ="$NOCOS_LIC_CNPJ" \
        NOCWORK_LICENSE_SECRET="$NOCOS_LIC_SECRET" \
        bash "$inst_script" "${extra_args[@]}" </dev/null
    else
        NOCWORK_LICENSE_MASTER_URL="$NOCOS_API_URL" \
        bash "$inst_script" "${extra_args[@]}" </dev/null
    fi

    unset NOCOS_LIC_SECRET
}

_nocos_ensure_enroll_pubkey() {
    local key_dir="/etc/nocwork"
    local priv_pem="${key_dir}/enroll_ed25519.pem"
    mkdir -p "$key_dir"
    chmod 0755 "$key_dir" 2>/dev/null || true
    if [ ! -s "$priv_pem" ]; then
        umask 077
        openssl genpkey -algorithm Ed25519 -out "$priv_pem" >/dev/null 2>&1 || return 1
        chmod 0600 "$priv_pem"
    fi
    # Extrai chave pública bruta (32 bytes Ed25519) do DER SubjectPublicKeyInfo em base64
    openssl pkey -in "$priv_pem" -pubout -outform DER 2>/dev/null | tail -c 32 | base64 -w0 2>/dev/null || \
        openssl pkey -in "$priv_pem" -pubout -outform DER 2>/dev/null | tail -c 32 | base64 | tr -d '\n'
}

_nocos_send_activation_email() {
    [ "$NOCOS_MODE" = "unclaimed" ] || return 0
    [ -n "$NOCOS_EMAIL" ] || return 0

    local pub_b64="" installed_ver="unclaimed"
    pub_b64=$(_nocos_ensure_enroll_pubkey 2>/dev/null || true)
    if [ -x /usr/local/sbin/nocwork ]; then
        installed_ver=$(/usr/local/sbin/nocwork --version 2>/dev/null | awk 'NR==1 {print $NF}' || echo "unclaimed")
    fi

    local endpoint="${NOCOS_API_URL%/}/v1/enroll/init"
    local payload resp http_code body
    payload=$(jq -cn \
        --arg machine_id "$NOCOS_HWID" \
        --arg pubkey "$pub_b64" \
        --arg hostname "$NOCOS_HOST" \
        --arg version "$installed_ver" \
        --arg email "$NOCOS_EMAIL" \
        '{machine_id:$machine_id, pubkey_ed25519:$pubkey, hostname:$hostname, version:$version, email:$email}')

    _nocos_info "Registrando máquina unclaimed e enviando código de ativação para $NOCOS_EMAIL..."
    resp=$(curl -sS -w "\n%{http_code}" --max-time 20 \
        -H "Content-Type: application/json" \
        -X POST "$endpoint" \
        -d "$payload" 2>/dev/null || true)
    http_code=$(printf '%s' "$resp" | tail -n 1)
    body=$(printf '%s' "$resp" | sed '$d')

    if [ "$http_code" = "404" ] || [ "$http_code" = "405" ]; then
        endpoint="${NOCOS_API_URL%/}/v1/activation/request"
        payload=$(jq -cn \
            --arg email "$NOCOS_EMAIL" \
            --arg hwid "$NOCOS_HWID" \
            --arg host "$NOCOS_HOST" \
            '{email:$email, machine_id:$hwid, hostname:$host}')
        resp=$(curl -sS -w "\n%{http_code}" --max-time 20 \
            -H "Content-Type: application/json" \
            -X POST "$endpoint" \
            -d "$payload" 2>/dev/null || true)
        http_code=$(printf '%s' "$resp" | tail -n 1)
        body=$(printf '%s' "$resp" | sed '$d')
    fi

    case "$http_code" in
        200|201|202)
            NOCOS_CLAIM_CODE=$(printf '%s' "$body" | jq -r '.code // .claim_code // empty' 2>/dev/null || true)
            NOCOS_CLAIM_URL=$(printf '%s' "$body" | jq -r '.claim_url // empty' 2>/dev/null || true)
            _nocos_ok "Código de ativação enviado para $NOCOS_EMAIL${NOCOS_CLAIM_CODE:+ (código: $NOCOS_CLAIM_CODE)}."
            ;;
        *)
            local err_msg
            err_msg=$(printf '%s' "$body" | jq -r '.error // empty' 2>/dev/null || true)
            _nocos_warn "Instalação concluída, mas o envio automático do código de ativação retornou HTTP ${http_code:-timeout}${err_msg:+ ($err_msg)}. Reivindique pelo portal usando o HWID $NOCOS_HWID."
            ;;
    esac
}

_nocos_summary() {
    echo
    printf '\033[1;32m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m\n'
    printf '  \033[1mNocOS instalado com sucesso\033[0m\n'
    printf '  Host / HWID:   %s (%s)\n' "$NOCOS_HOST" "$NOCOS_HWID"
    if [ -n "${NOCOS_TLS_DOMAIN:-}" ]; then
        printf '  Painel HTTPS:  https://%s:%s\n' "$NOCOS_TLS_DOMAIN" "$NOCOS_HTTPS_PORT"
    else
        local ip_local
        ip_local=$(hostname -I 2>/dev/null | awk '{print $1}')
        printf '  Painel HTTPS:  https://%s:%s\n' "${ip_local:-127.0.0.1}" "$NOCOS_HTTPS_PORT"
    fi
    if [ "$NOCOS_MODE" = "token" ]; then
        if [ "${NOCOS_IS_TRIAL:-false}" = "true" ] && [ -n "${NOCOS_EXPIRES_AT:-}" ]; then
            printf '  Licença:       Trial (%s · válido até %s)\n' "$NOCOS_LIC_ID" "$NOCOS_EXPIRES_AT"
        else
            printf '  Licença:       Ativa (%s)\n' "$NOCOS_LIC_ID"
        fi
    else
        printf '  Licença:       Unclaimed (pronta para ativação em https://portal.nocos.com.br/ativar)\n'
        [ -n "$NOCOS_CLAIM_CODE" ] && printf '  Código:        %s\n' "$NOCOS_CLAIM_CODE"
        [ -n "$NOCOS_CLAIM_URL" ] && printf '  Link Claim:    %s\n' "$NOCOS_CLAIM_URL"
        [ -n "$NOCOS_EMAIL" ] && printf '  Ativação:      Código solicitado para %s\n' "$NOCOS_EMAIL"
    fi
    printf '\033[1;32m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m\n'
}

main() {
    _nocos_parse_args "$@"
    echo
    printf '\033[1;33m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m\n'
    printf '  \033[1mNocOS · Instalador Oficial (Debian 12/13)\033[0m\n'
    printf '\033[1;33m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m\n'

    _nocos_preflight
    _nocos_compute_hwid

    if [ "$NOCOS_MODE" = "token" ]; then
        _nocos_claim_token
    else
        _nocos_prompt_optional_email
    fi

    _nocos_run_install
    _nocos_send_activation_email
    _nocos_summary
}

main "$@"
