#!/usr/bin/env bash
# 下载并执行 install-nexus-fresh.sh（公共仓库无需令牌）
#
#   curl -fsSL "http://66.154.115.8:3000/admin/Nexus/raw/branch/main/deploy/download-install-fresh.sh" | bash
#
# 推荐直接使用:
#   curl -fsSL "http://66.154.115.8:3000/admin/Nexus/raw/branch/main/deploy/quick-install.sh" | bash

set -euo pipefail

NEXUS_GITEA_HOST="${NEXUS_GITEA_HOST:-66.154.115.8:3000}"
NEXUS_GIT_BRANCH="${NEXUS_GIT_BRANCH:-main}"
NEXUS_RAW_BASE="${NEXUS_RAW_BASE:-http://${NEXUS_GITEA_HOST}/admin/Nexus/raw/branch/${NEXUS_GIT_BRANCH}}"
OUT="${OUT:-/tmp/install-nexus-fresh.sh}"

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

err() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
ok()  { echo -e "${GREEN}[OK]${NC} $*"; }

for cf in /root/.nexus-deploy.env /root/.nexus-secrets/nexus.env; do
    [[ -f "$cf" ]] && set -a && source "$cf" && set +a
done

download() {
    local url base
    for base in "${NEXUS_RAW_BASE}" "http://${NEXUS_GITEA_HOST}/admin/Nexus/raw/${NEXUS_GIT_BRANCH}"; do
        url="${base}/deploy/install-nexus-fresh.sh"
        if curl -fsSL "$url" -o "$OUT" 2>/dev/null && head -1 "$OUT" | grep -q '^#!/'; then
            ok "已下载 install-nexus-fresh.sh"
            chmod +x "$OUT"
            exec bash "$OUT" "$@"
        fi
    done
    if [[ -n "${NEXUS_GITEA_TOKEN:-}" ]]; then
        url="http://${NEXUS_GITEA_HOST}/api/v1/repos/admin/Nexus/raw/deploy/install-nexus-fresh.sh?ref=${NEXUS_GIT_BRANCH}"
        if curl -fsSL -H "Authorization: token ${NEXUS_GITEA_TOKEN}" "$url" -o "$OUT" 2>/dev/null \
            && head -1 "$OUT" | grep -q '^#!/'; then
            ok "已下载（API + 令牌）"
            chmod +x "$OUT"
            exec bash "$OUT" "$@"
        fi
    fi
    return 1
}

if ! download "$@"; then
    err "下载失败，请改用公共仓库一键入口:"
    err "  curl -fsSL \"${NEXUS_RAW_BASE}/deploy/quick-install.sh\" | bash"
    exit 1
fi
