#!/bin/bash
# Downloaded from the public installer door: the door is tried first.
export MSEASY_SERVER=https://kit.nz.objectivize.net
# ═══════════════════════════════════════════════════════════════════
# MSEasy Developer Pack — Bootstrap (macOS)
#
# Preferred: open Terminal and run   bash Install-MSEasy-macOS.command
# (Double-clicking a downloaded script is blocked by macOS Gatekeeper
# — "unidentified developer" — and browser downloads can strip the
# executable flag. Running it through bash avoids both.)
#
# Self-contained: this file is the complete macOS bootstrap — it does
# not call any other script. Keep the logic in sync with its twin,
# Install-MSEasy-Linux.sh.
#
# Install is online: this tiny bootstrap pulls everything from the MSEasy
# server — the pinned UV, the latest installer, and (via UV's --mirror) the
# Python 3.14 standalone build. Nothing heavy is bundled.
#   1. Find the MSEasy server (clinic LAN → the MSEasy network → its public door)
#   2. Get UV (a system copy, else the pinned UV from the server)
#   3. Download the latest install_mseasy.py from the server
#   4. Run it with UV's Python 3.14 (pulled from the server's mirror)
# ═══════════════════════════════════════════════════════════════════

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
INSTALLER="$SCRIPT_DIR/install_mseasy.py"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'

info()  { echo -e "${BLUE}[INFO]${NC}  $*"; }
ok()    { echo -e "${GREEN}[OK]${NC}    $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $*"; }
fail()  { echo -e "${RED}[FAIL]${NC}  $*"; exit 1; }

echo ""
echo -e "${BOLD}MSEasy Developer Pack — Bootstrap (macOS)${NC}"
echo ""

# ── Step 0: Clear macOS quarantine on the DevPack files ──────────
# Browser-downloaded files carry com.apple.quarantine, which makes every
# double-click hit Gatekeeper. We're already running (via bash), so strip it
# from the extracted DevPack folder — future runs can then simply be
# double-clicked in Finder.
xattr -dr com.apple.quarantine "$SCRIPT_DIR" 2>/dev/null || true

# ── Step 1: Find the MSEasy server ───────────────────────────────
# Install needs the server for everything (UV, installer, Python, app bundle),
# so there's no offline path — locate it first and fail with clear guidance.
info "Looking for the MSEasy server ..."
# The public door before the LAN: ONE path for everyone not yet on the
# network, the path a stranger gets; the private addresses when the house
# has no internet. (A copy downloaded from the door sets MSEASY_SERVER too.)
MSEASY_DOOR="https://kit.nz.objectivize.net"
SERVER=""
for cand in "${MSEASY_SERVER:-}" "http://mseasy-server.mesh.nz.objectivize.net:8000" "http://100.64.0.1:8000" "$MSEASY_DOOR" "http://10.0.0.2:8000" "http://mseasy-server:8000" "http://100.78.68.39:8000"; do
    [[ -z "$cand" ]] && continue
    cand="${cand%/}"
    wait=4; [[ "$cand" == https://* ]] && wait=15
    if curl -sf --max-time $wait "$cand/health" -o /dev/null 2>/dev/null; then
        SERVER="$cand"
        ok "Server found: $SERVER"
        break
    fi
done

if [[ -z "$SERVER" ]]; then
    echo ""
    fail "Cannot reach MSEasy anywhere — not even its public door ($MSEASY_DOOR).
  Check this computer's internet connection — and its CLOCK: a wrong time or date
  fails every encrypted connection. Then run this installer again."
fi

# ── Step 2: Get UV — a system copy, else the pinned UV from server ─
UV_BIN=""
ARCH="$(uname -m)"

# 2a) Prefer an existing UV on PATH / common locations
for candidate in \
    "$(command -v uv 2>/dev/null)" \
    "$HOME/.local/bin/uv" \
    "$HOME/.cargo/bin/uv" \
    "/usr/local/bin/uv" \
    "/opt/homebrew/bin/uv"; do
    if [[ -n "$candidate" && -x "$candidate" ]]; then
        UV_BIN="$candidate"
        ok "Using existing UV: $UV_BIN"
        break
    fi
done

# 2b) Otherwise download the pinned UV from the server
if [[ -z "$UV_BIN" ]]; then
    if [[ "$ARCH" == "arm64" ]]; then
        UV_NAME="uv-macos-arm"
    else
        UV_NAME="uv-macos-x86"
    fi
    UV_BIN="$SCRIPT_DIR/uv"
    info "Downloading UV ($UV_NAME) from server ..."
    curl -sf --max-time 120 "$SERVER/install/uv/$UV_NAME" -o "$UV_BIN" \
        || fail "Could not download UV from $SERVER"
    chmod +x "$UV_BIN"
    ok "UV ready: $UV_BIN"
fi

# ── Step 3: Get the latest installer from the server ─────────────
# Always pull the newest install_mseasy.py so every install gets current fixes.
info "Downloading latest installer ..."
if curl -sf --max-time 30 "$SERVER/install/installer/unified" -o "$INSTALLER.tmp"; then
    mv -f "$INSTALLER.tmp" "$INSTALLER"
    chmod +x "$INSTALLER"
    ok "Installer ready"
else
    rm -f "$INSTALLER.tmp" 2>/dev/null || true
    fail "Could not download installer from $SERVER"
fi

# ── Step 4: Run the installer with UV's Python 3.14 ──────────────
# Point UV at the server's Python mirror so it pulls the standalone build from
# the MSEasy server (no general-internet needed). Pass the discovered server so
# install_mseasy.py doesn't have to re-probe.
export MSEASY_SERVER="$SERVER"
export UV_PYTHON_INSTALL_MIRROR="$SERVER/install/python-mirror"

info "Launching MSEasy installer ..."
echo ""
"$UV_BIN" run --python 3.14 "$INSTALLER" "$@"
