#!/usr/bin/env bash
# Install Hydrogen Desktop (macOS) — downloads the signed DMG release asset from the
# wiki (verifying its SHA-256), mounts it, and copies the app to /Applications. On
# first launch the app downloads its own VM runtime + workspace image automatically,
# so setup runs with no extra installs and no clicks.
#
# Apple Silicon only (arm64). Runs from the extracted package dir (adom-wiki pkg).
set -euo pipefail

VERSION="0.1.135"
DMG_NAME="Hydrogen.Desktop_${VERSION}_aarch64.dmg"
DMG_URL="https://wiki.adom.inc/download/adom/hydrogen-desktop-macos/${VERSION}/${DMG_NAME}"
DMG_SHA256="b2bc43246782044779fcc47e91c95a25ef88287191467f237d9a2ab683051931"

if [ "$(uname)" != "Darwin" ]; then
  echo "ERROR: Hydrogen Desktop (macOS) installs only on macOS." >&2; exit 1
fi
if [ "$(uname -m)" != "arm64" ]; then
  echo "ERROR: this build is Apple Silicon (arm64) only." >&2; exit 1
fi

# Prefer a bundled DMG if one shipped in the package (older tarballs did this);
# otherwise download the pinned release asset and verify it.
DMG="$(ls dist/macos/*.dmg 2>/dev/null | head -1 || true)"
if [ -z "$DMG" ]; then
  DL_DIR="$(mktemp -d)"
  DMG="$DL_DIR/$DMG_NAME"
  echo "Downloading $DMG_NAME …"
  curl -fL --retry 3 -o "$DMG" "$DMG_URL"
  echo "$DMG_SHA256  $DMG" | shasum -a 256 -c - >/dev/null || {
    echo "ERROR: SHA-256 mismatch on downloaded DMG." >&2; exit 1; }
fi

MNT="$(mktemp -d)"
cleanup() { hdiutil detach "$MNT" >/dev/null 2>&1 || true; }
trap cleanup EXIT

echo "Mounting $DMG …"
hdiutil attach "$DMG" -nobrowse -mountpoint "$MNT" >/dev/null
APP="$(ls -d "$MNT"/*.app 2>/dev/null | head -1)"
[ -n "$APP" ] || { echo "ERROR: no .app inside the DMG." >&2; exit 1; }

DEST="/Applications/$(basename "$APP")"
echo "Installing $(basename "$APP") to /Applications …"
rm -rf "$DEST"
cp -R "$APP" /Applications/
# Drop the quarantine flag so first launch isn't blocked by Gatekeeper. NOTE: this
# build is signed (Developer ID) but not yet notarized — until it is, macOS may still
# warn on first open (right-click → Open once). See the README.
xattr -dr com.apple.quarantine "$DEST" 2>/dev/null || true

echo "OK: installed $DEST"
echo "Launch it from /Applications or Spotlight. First run sets everything up automatically."