#!/usr/bin/env bash
# Install Adom Hydrogen (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.239"
DMG_NAME="Adom.Hydrogen_${VERSION}_aarch64.dmg"
DMG_URL="https://wiki.adom.inc/download/adom/hydrogen-macos/${VERSION}/${DMG_NAME}"
DMG_SHA256="04d69e42ccda0d053dc63747c78c5e67adb6e1456a37deacdc00d807e40f548a"

if [ "$(uname)" != "Darwin" ]; then
  echo "ERROR: Adom Hydrogen (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, notarized, and stapled — Gatekeeper opens it without warnings.
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."
