#!/usr/bin/env bash
# Copyright (c) 2026 the Zuke contributors
# SPDX-License-Identifier: MIT
#
# Zuke launcher for a build another SDK hosts.
#
#   ./zuke               # run the default target
#   ./zuke <target>      # run one target and its prerequisites
#   ./zuke --list        # list every target
#
# Runs zuke 2.4.0, which carries the engine and every tool wrapper, so
# this project needs nothing installed but its own SDK's tools. On first use
# it downloads that release, checksum-verified, into ZUKE_INSTALL.
#
# Honoured environment variables:
#   ZUKE_INSTALL       where zuke releases are kept (default: ~/.zuke)
#   ZUKE_RELEASES_URL  a mirror of https://github.com/zuke-build/zuke/releases/download;
#                      what it serves is verified against the pins below
set -euo pipefail

dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
cd "$dir"

# The pinned release, and the SHA-256 of each platform's archive, from the
# SHA256SUMS of https://github.com/zuke-build/zuke/releases/download/cli-v2.4.0.
# Moved by `zuke upgrade --engine`, which rewrites this file; never hand-edit.
ZUKE_VERSION="2.4.0"
zuke_checksum_for() {
  case "$1" in
    aarch64-apple-darwin)
      echo "925f71aac4cfe8e7fe3e15266f32732f7fe533d240c30142e3b428116f9afe0c" ;;
    x86_64-apple-darwin)
      echo "9f8bea39f96502d3f2987685328c3650273326884c90a74cca90e5b311239dc8" ;;
    aarch64-unknown-linux-gnu)
      echo "b62aa9ec9065a6990693448833b169d5ae31894715b737bfdc2521c6fb13315e" ;;
    x86_64-unknown-linux-gnu)
      echo "c7fefb3291b1d4bb697b72b832864642f97c142d923d9dd380d73201652595f2" ;;
    *)
      return 1 ;;
  esac
}

zuke_install="${ZUKE_INSTALL:-$HOME/.zuke}"
zuke_bin="$zuke_install/releases/$ZUKE_VERSION/zuke"

if [ ! -x "$zuke_bin" ]; then
  echo "zuke: zuke $ZUKE_VERSION is not here yet — downloading it..." >&2
  for cmd in curl tar; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
      echo "zuke: $cmd is required to download zuke; install zuke instead:" >&2
      echo "      https://github.com/zuke-build/zuke/blob/master/docs/install.md" >&2
      exit 1
    fi
  done

  # Map uname's OS/arch spelling to the release's target triple.
  case "$(uname -s)" in
    Linux) os_part="unknown-linux-gnu" ;;
    Darwin) os_part="apple-darwin" ;;
    *)
      echo "zuke: no zuke release is built for $(uname -s); use zuke.ps1 on Windows." >&2
      exit 1
      ;;
  esac
  case "$(uname -m)" in
    x86_64 | amd64) arch_part="x86_64" ;;
    arm64 | aarch64) arch_part="aarch64" ;;
    *)
      echo "zuke: no zuke release is built for the $(uname -m) architecture." >&2
      exit 1
      ;;
  esac
  target="${arch_part}-${os_part}"
  expected_sha256="$(zuke_checksum_for "$target")" || {
    echo "zuke: no pinned checksum for $target." >&2
    exit 1
  }

  asset="zuke-${ZUKE_VERSION}-${target}.tar.gz"
  download_url="${ZUKE_RELEASES_URL:-https://github.com/zuke-build/zuke/releases/download}/cli-v${ZUKE_VERSION}/${asset}"
  work_dir="$(mktemp -d)"
  trap 'rm -rf "$work_dir"' EXIT
  archive="$work_dir/$asset"

  # The network is occasionally flaky (a transient 5xx from the CDN), so a blip
  # is retried with backoff rather than failing the run.
  attempt=1
  max_attempts=4
  until curl -fsSL -o "$archive" "$download_url"; do
    if [ "$attempt" -ge "$max_attempts" ]; then
      echo "zuke: failed to download $download_url after $max_attempts attempts." >&2
      exit 1
    fi
    delay=$((attempt * 3))
    echo "zuke: download failed (attempt $attempt/$max_attempts); retrying in ${delay}s..." >&2
    sleep "$delay"
    attempt=$((attempt + 1))
  done

  if command -v sha256sum >/dev/null 2>&1; then
    actual_sha256="$(sha256sum "$archive" | awk '{print $1}')"
  elif command -v shasum >/dev/null 2>&1; then
    actual_sha256="$(shasum -a 256 "$archive" | awk '{print $1}')"
  else
    echo "zuke: neither sha256sum nor shasum is available to verify the download." >&2
    exit 1
  fi
  if [ "$actual_sha256" != "$expected_sha256" ]; then
    echo "zuke: checksum mismatch for $asset:" >&2
    echo "      expected $expected_sha256" >&2
    echo "      got      $actual_sha256" >&2
    exit 1
  fi

  tar -xzf "$archive" -C "$work_dir" zuke
  mkdir -p "$(dirname "$zuke_bin")"
  # Moved into place in one step, so a run interrupted mid-copy never leaves a
  # binary behind that later runs would trust without verifying.
  mv -f "$work_dir/zuke" "$zuke_bin.$$"
  chmod +x "$zuke_bin.$$"
  mv -f "$zuke_bin.$$" "$zuke_bin"
  # Removed now: the exec below replaces this shell, so the trap never fires.
  rm -rf "$work_dir"
  trap - EXIT
fi

# zuke runs the build here itself rather than this launcher again, and does not
# hold this directory to the trust gate: running the launcher named it.
export ZUKE_FORWARDED=1
export ZUKE_LAUNCHER_ROOT="$dir"
exec "$zuke_bin" "$@"
