#!/bin/bash
set -euo pipefail

expected_sha256="bea6ce18eb1ff2fc76d68e94f2666492335a711667f0edbc3829875e57c1c9d0"
download_urls=(
  "https://marvis48-test-download.pages.dev/Marvis-48GB-Test.zip"
  "https://raw.githubusercontent.com/zhaoyu190/marvis48-test-download/main/Marvis-48GB-Test.zip"
)

temp_root="${TMPDIR:-/tmp}"
temp_root="${temp_root%/}"
temp_dir="$(mktemp -d "${temp_root}/marvis48-download.XXXXXX")"
archive="${temp_dir}/Marvis-48GB-Test.zip"

cleanup() {
  rm -f -- "$archive"
  rmdir -- "$temp_dir" 2>/dev/null || true
}
trap cleanup EXIT INT TERM

echo "正在下载 Marvis 48GB 测试启动器……"
downloaded=false
for download_url in "${download_urls[@]}"; do
  if curl --proto '=https' --tlsv1.2 -fL --retry 2 "$download_url" -o "$archive"; then
    downloaded=true
    break
  fi
done

if [[ "$downloaded" != "true" ]]; then
  echo "下载失败，请稍后重试。"
  exit 1
fi

actual_sha256="$(shasum -a 256 "$archive" | awk '{print $1}')"
if [[ "$actual_sha256" != "$expected_sha256" ]]; then
  echo "文件校验失败，已停止解压。"
  echo "实际 SHA-256：$actual_sha256"
  exit 1
fi

destination="${HOME}/Downloads/Marvis-48GB-Test"
if [[ -e "$destination" ]]; then
  destination="${destination}-$(date +%Y%m%d-%H%M%S)"
fi

mkdir -p "$destination"
/usr/bin/ditto -x -k "$archive" "$destination"

app_path="${destination}/Marvis-48GB-Test.app"
echo
echo "下载与校验完成："
echo "$app_path"
echo
echo "请先完全退出官方 Marvis，再右键点击测试启动器并选择“打开”。"
/usr/bin/open -R "$app_path"
