#!/bin/sh
#
# macos-build.sh — build Lantern on a macOS aarch64 host via SSH.
#
# Invoked by GitLab CI with:
#   ssh gitlab-ci@100.100.220.0 "REF='...' VERSION='...' sh -s" < scripts/macos-build.sh
#
# The script clones the repo at the requested commit, builds a release binary,
# and leaves it at ~/lantern/target/release/lantern for the CI job to SCP.
# Rust is installed to ~/rust/ on the first run (persists across builds).
#
set -e

REF="${REF:-main}"
VERSION="${VERSION:-}"

REPO_URL="https://git.skylantix.com/diogenes/lantern.git"
BUILD_DIR="$HOME/lantern"
RUST_HOME="$HOME/rust"

# ── Rust toolchain ──────────────────────────────────────────────────────────
if [ ! -x "$RUST_HOME/bin/rustc" ]; then
  echo ">>> Installing Rust to $RUST_HOME ..."
  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
    | sh -s -- -y --default-toolchain stable --no-modify-path
fi
export PATH="$RUST_HOME/bin:$PATH"
rustup default stable
rustup update stable

# ── Clone and build ────────────────────────────────────────────────────────
rm -rf "$BUILD_DIR"
git clone --depth 1 "$REPO_URL" "$BUILD_DIR"
cd "$BUILD_DIR"
git fetch origin "$REF"
git checkout "$REF"

if [ -n "$VERSION" ]; then
  sed -i '' "s/^version = .*/version = \"${VERSION}\"/" Cargo.toml
fi

cargo build --release

echo ">>> Build complete: $BUILD_DIR/target/release/lantern"
ls -la "$BUILD_DIR/target/release/lantern"
file "$BUILD_DIR/target/release/lantern"
