#!/usr/bin/env bash
set -euo pipefail

BASE_URL="${BASE_URL:-https://cdn.cubenet.me/launcher}"
LAUNCHER_VERSION="${LAUNCHER_VERSION:-0.4.0}"
BOOTSTRAPPER_VERSION="${BOOTSTRAPPER_VERSION:-0.4.4}"
INSTALL_ROOT="${INSTALL_ROOT:-$HOME/.cubenet/bin}"

detect_channel() {
  local arch
  arch="$(uname -m)"
  case "$arch" in
    arm64|aarch64)
      echo "macos-arm64"
      ;;
    x86_64)
      echo "macos-x64"
      ;;
    *)
      echo "Unsupported macOS architecture: $arch" >&2
      exit 1
      ;;
  esac
}

download() {
  local url="$1"
  local out="$2"
  curl -fL --retry 3 --connect-timeout 15 "$url" -o "$out"
}

verify_sha256() {
  local file="$1"
  local expected="$2"
  local actual
  actual="$(shasum -a 256 "$file" | awk '{print $1}')"
  if [[ "$actual" != "$expected" ]]; then
    echo "SHA256 mismatch for $file" >&2
    echo "Expected: $expected" >&2
    echo "Actual:   $actual" >&2
    exit 1
  fi
}

channel="$(detect_channel)"

case "$channel" in
  macos-arm64)
    launcher_sha="be71acbe842d052e283d3e74c6965c1687e4afc2f28135876eb7d859b8c687f5"
    bootstrapper_sha="1e561c56417fc473e1aece218b9317e011be341186fcd5e052068d37aaa508d0"
    ;;
  macos-x64)
    launcher_sha="d2f42ca7babce0ae284430173033af93235d85ede5c0fa0a0254ecfeb7702953"
    bootstrapper_sha="04208c0a72c6b173b0e42d854327aa98c23853829139eb32b4f621e24af1089a"
    ;;
esac

launcher_url="${BASE_URL}/releases/${LAUNCHER_VERSION}/${channel}/newlauncher"
bootstrapper_url="${BASE_URL}/bootstrapper/${BOOTSTRAPPER_VERSION}/${channel}/cubenet_launcher"

mkdir -p "$INSTALL_ROOT"

launcher_path="${INSTALL_ROOT}/newlauncher"
bootstrapper_path="${INSTALL_ROOT}/cubenet_launcher"

echo "Installing Cubenet Launcher for ${channel}..."
echo "Launcher URL: $launcher_url"
echo "Bootstrapper URL: $bootstrapper_url"

download "$launcher_url" "$launcher_path"
download "$bootstrapper_url" "$bootstrapper_path"

verify_sha256 "$launcher_path" "$launcher_sha"
verify_sha256 "$bootstrapper_path" "$bootstrapper_sha"

chmod +x "$launcher_path" "$bootstrapper_path"
xattr -dr com.apple.quarantine "$INSTALL_ROOT" || true

echo "Starting bootstrapper..."
exec "$bootstrapper_path"
