#!/bin/sh
# fbb one-shot bootstrap for Linux / macOS (design ch.2.1 / 4.2.4).
#
# Brings a bare machine to "ready to build" entirely from the self-hosted OBS:
#   1. download uv from OBS  ->  ~/.local/bin
#   2. uv tool install fbb
#   3. point uv's Python mirror at OBS, then run `fbb setup`
#
# No github.com / astral.sh dependency for the common platforms (uv comes from
# dl.hispark.hisilicon.com). Platforms without an OBS uv artifact fall back to
# the upstream astral installer.
#
# Usage:
#   curl -fsSL https://dl.hispark.hisilicon.com/bootstrap.sh | sh
#   ./bootstrap.sh --chips ws63 --fbb-source /path/to/hs-fbb-cli --force
set -eu

OBS_BASE="https://dl.hispark.hisilicon.com"
FBB_SOURCE="git+https://gitcode.com/HiSpark/hs-fbb-cli.git"
CHIPS=""
PIP_INDEX="https://pypi.tuna.tsinghua.edu.cn/simple"
FORCE=""

while [ $# -gt 0 ]; do
    case "$1" in
        --obs-base)   OBS_BASE="$2"; shift 2 ;;
        --fbb-source) FBB_SOURCE="$2"; shift 2 ;;
        --chips)      CHIPS="$2"; shift 2 ;;
        --pip-index)  PIP_INDEX="$2"; shift 2 ;;
        --force)      FORCE="--force"; shift ;;
        *) echo "[bootstrap] unknown arg: $1" >&2; exit 2 ;;
    esac
done

info() { printf '\033[36m[bootstrap]\033[0m %s\n' "$1"; }
ok()   { printf '\033[32m[bootstrap]\033[0m %s\n' "$1"; }
warn() { printf '\033[33m[bootstrap]\033[0m %s\n' "$1"; }

# ---- 0. platform → manifest tag + uv URL ---------------------------------
OS="$(uname -s)"; ARCH="$(uname -m)"
case "$OS-$ARCH" in
    Linux-x86_64)                TAG="linux-x86_64";  UV_FALLBACK="uv-0.11.17-linux-x86_64.tar.gz" ;;
    Linux-aarch64|Linux-arm64)   TAG="linux-aarch64"; UV_FALLBACK="" ;;
    Darwin-arm64|Darwin-aarch64) TAG="darwin-arm64";  UV_FALLBACK="uv-0.11.17-darwin-arm64.tar.gz" ;;
    *) TAG=""; UV_FALLBACK=""; warn "no OBS uv artifact for $OS-$ARCH; will fall back to upstream installer" ;;
esac

# Resolve the uv URL from the manifest (artifact 'url' is authoritative, so
# renames don't break bootstrap). Needs python3; falls back to the conventional
# path, then to the upstream astral installer.
UV_URL=""
if [ -n "$TAG" ] && command -v python3 >/dev/null 2>&1; then
    UV_URL="$(python3 - "$OBS_BASE/tools.json" "$TAG" <<'PY' 2>/dev/null || true
import json, sys, urllib.request
url, tag = sys.argv[1], sys.argv[2]
try:
    raw = urllib.request.urlopen(url, timeout=20).read().decode('utf-8-sig')
    print(json.loads(raw)['tools']['uv']['versions'][0]['platforms'].get(tag, {}).get('url', ''))
except Exception:
    pass
PY
)"
fi
[ -z "$UV_URL" ] && [ -n "$UV_FALLBACK" ] && UV_URL="$OBS_BASE/fbb-tools/uv/$UV_FALLBACK"
[ -z "$UV_URL" ] && [ -n "$TAG" ] && warn "no OBS uv artifact listed for $TAG; will fall back to upstream installer"

BIN_DIR="$HOME/.local/bin"
mkdir -p "$BIN_DIR"

# ---- 1. uv ----------------------------------------------------------------
UV_ART=""                       # non-empty once uv is obtained from OBS
if [ -n "$UV_URL" ]; then
    UV_ART="uv"
    TMP="$(mktemp -d)"
    info "downloading uv: $UV_URL"
    if curl -fsSL "$UV_URL" -o "$TMP/uv.tgz"; then
        tar -xzf "$TMP/uv.tgz" -C "$TMP"
        UVBIN="$(find "$TMP" -type f -name uv | head -n1)"
        [ -n "$UVBIN" ] || { warn "uv not found in archive; falling back"; UV_ART=""; }
        if [ -n "$UVBIN" ]; then
            cp "$UVBIN" "$BIN_DIR/uv"
            UVXBIN="$(find "$TMP" -type f -name uvx | head -n1)"
            [ -n "$UVXBIN" ] && cp "$UVXBIN" "$BIN_DIR/uvx" || true
            chmod +x "$BIN_DIR/uv" "$BIN_DIR/uvx" 2>/dev/null || true
        fi
    else
        warn "OBS uv download failed; falling back to upstream installer"
        UV_ART=""
    fi
    rm -rf "$TMP"
fi
if [ -z "$UV_ART" ] && ! command -v uv >/dev/null 2>&1; then
    info "installing uv via upstream astral installer"
    curl -LsSf https://astral.sh/uv/install.sh | sh
fi
export PATH="$BIN_DIR:$PATH"
ok "uv ready ($(uv --version))"

# ---- 2. fbb via uv --------------------------------------------------------
export UV_INDEX_URL="$PIP_INDEX"
info "installing fbb from: $FBB_SOURCE"
uv tool install --force "$FBB_SOURCE"
uv tool update-shell 2>/dev/null || true
ok "fbb installed ($(fbb --version 2>/dev/null || echo '?'))"

# ---- 3. fbb setup ---------------------------------------------------------
export FBB_OBS_BASE="$OBS_BASE"
export UV_PYTHON_INSTALL_MIRROR="$OBS_BASE/fbb-tools/python"
export FBB_PIP_INDEX="$PIP_INDEX"
set -- setup
[ -n "$CHIPS" ] && set -- "$@" --targets "$CHIPS"
[ -n "$FORCE" ] && set -- "$@" "$FORCE"
info "running: fbb $*"
fbb "$@"

ok "done. Try:  fbb doctor   then   fbb build <target>"