#!/bin/sh
# ============================================================
# Lith Launcher — macOS installer
# ============================================================
#
# What this does:
#   1. Checks you're on an Apple Silicon Mac.
#   2. Finds the latest Lith Launcher .dmg on GitHub.
#   3. Downloads it, mounts it, and copies the app into /Applications
#      (or ~/Applications if that isn't writable).
#   4. Clears the macOS quarantine flag so you DON'T get the false
#      "app is damaged and can't be opened" warning that Apple shows
#      for apps whose developer doesn't pay the $99/yr Apple tax.
#   5. Opens the launcher.
#
# This script is intentionally short and reviewable — read it before
# running it. If you'd rather install by hand, see:
#   https://www.lith.cat/download
#
# Usage:  curl -fsSL https://lith.cat/install-mac.sh | sh
#
# Note: this runs as `curl | sh`, so stdin is the pipe, not your
# keyboard — the script is fully non-interactive (no prompts).
# ============================================================

set -eu

RELEASES_PAGE="https://github.com/LithMS/Lith-Artifacts/releases"
API_LATEST="https://api.github.com/repos/LithMS/Lith-Artifacts/releases/latest"
API_LIST="https://api.github.com/repos/LithMS/Lith-Artifacts/releases?per_page=100"
APP_NAME="Lith Launcher.app"

say()  { printf '\n\033[1;36m==>\033[0m %s\n' "$1"; }
info() { printf '    %s\n' "$1"; }
warn() { printf '\n\033[1;33m!\033[0m %s\n' "$1" >&2; }
die()  { printf '\n\033[1;31mError:\033[0m %s\n' "$1" >&2; exit 1; }

# ── Guard rails ──────────────────────────────────────────────
say "Checking your Mac"

[ "$(uname -s)" = "Darwin" ] || die "This installer is for macOS only. Detected: $(uname -s)."

if [ "$(uname -m)" != "arm64" ]; then
  die "Lith Launcher for macOS requires Apple Silicon (M1 or newer). Intel Macs aren't supported yet. See $RELEASES_PAGE"
fi
info "Apple Silicon macOS detected."

# ── Resolve the .dmg download URL (no jq) ────────────────────
# Prefer the 'latest' release; fall back to the newest release in the
# list (prereleases included) that ships an arm64 dmg.
say "Finding the latest Lith Launcher build"

# Pull the first browser_download_url ending in -arm64.dmg out of a JSON blob.
extract_dmg_url() {
  printf '%s' "$1" | grep -o 'https://[^"]*-arm64\.dmg' | head -n 1
}

# Fetch both endpoints up front so a GitHub failure (rate limit, outage) is
# distinguishable from "no macOS build exists".
LATEST_JSON="$(curl -fsSL "$API_LATEST" 2>/dev/null)" || LATEST_JSON=""
LIST_JSON="$(curl -fsSL "$API_LIST" 2>/dev/null)" || LIST_JSON=""

if [ -z "$LATEST_JSON" ] && [ -z "$LIST_JSON" ]; then
  die "Couldn't reach GitHub to look up the launcher (rate limit or outage?). Try again in a few minutes, or download manually from $RELEASES_PAGE"
fi

DMG_URL="$(extract_dmg_url "$LATEST_JSON")"
if [ -z "${DMG_URL:-}" ]; then
  info "No macOS build in the latest release; checking recent releases…"
  DMG_URL="$(extract_dmg_url "$LIST_JSON")"
fi

[ -n "${DMG_URL:-}" ] || die "Couldn't find a macOS (.dmg) build. Download it manually from $RELEASES_PAGE"
info "Found: $DMG_URL"

# ── Download to a temp dir with cleanup ──────────────────────
WORKDIR="$(mktemp -d)"
MOUNTPOINT=""

cleanup() {
  # Detach the dmg if still mounted, then remove the temp dir.
  if [ -n "$MOUNTPOINT" ] && [ -d "$MOUNTPOINT" ]; then
    hdiutil detach "$MOUNTPOINT" -quiet >/dev/null 2>&1 || true
  fi
  [ -n "${WORKDIR:-}" ] && rm -rf "$WORKDIR"
}
trap cleanup EXIT

DMG_PATH="$WORKDIR/LithLauncher.dmg"

say "Downloading the launcher"
curl -fL --progress-bar "$DMG_URL" -o "$DMG_PATH" \
  || die "Download failed. Check your connection and try again, or download manually from $RELEASES_PAGE"

# ── Mount the dmg ────────────────────────────────────────────
say "Mounting the disk image"
# -nobrowse: don't show it in Finder; -readonly: don't touch the image.
ATTACH_OUT="$(hdiutil attach "$DMG_PATH" -nobrowse -readonly 2>/dev/null)" \
  || die "Couldn't mount the disk image."

# The mount point is the last whitespace-run-separated field on the /Volumes line.
MOUNTPOINT="$(printf '%s\n' "$ATTACH_OUT" | grep -o '/Volumes/.*' | head -n 1)"
[ -n "$MOUNTPOINT" ] && [ -d "$MOUNTPOINT" ] || die "Couldn't determine where the disk image mounted."
info "Mounted at $MOUNTPOINT"

# ── Locate the .app bundle on the volume ─────────────────────
SRC_APP=""
for candidate in "$MOUNTPOINT"/*.app; do
  if [ -d "$candidate" ]; then
    SRC_APP="$candidate"
    break
  fi
done
[ -n "$SRC_APP" ] || die "No .app bundle found inside the disk image."
info "Found $(basename "$SRC_APP")"

# ── Choose an install destination ────────────────────────────
DEST_DIR="/Applications"
if [ ! -w "$DEST_DIR" ]; then
  DEST_DIR="$HOME/Applications"
  warn "/Applications isn't writable. Installing to $DEST_DIR instead."
  mkdir -p "$DEST_DIR"
fi
DEST_APP="$DEST_DIR/$APP_NAME"

# ── Refuse to clobber a running copy ─────────────────────────
if pgrep -f "$DEST_APP/Contents/MacOS/" >/dev/null 2>&1; then
  die "Lith Launcher looks like it's running. Quit it, then re-run this installer."
fi

# ── Install ──────────────────────────────────────────────────
say "Installing to $DEST_DIR"
if [ -e "$DEST_APP" ]; then
  info "Removing the previous version…"
  rm -rf "$DEST_APP"
fi

if command -v ditto >/dev/null 2>&1; then
  ditto "$SRC_APP" "$DEST_APP"
else
  cp -R "$SRC_APP" "$DEST_APP"
fi
info "Copied the app."

# ── Detach the dmg (cleanup retries if the volume is busy) ───
if hdiutil detach "$MOUNTPOINT" -quiet >/dev/null 2>&1; then
  MOUNTPOINT=""
fi

# ── Clear quarantine so Gatekeeper doesn't cry "damaged" ─────
say "Clearing the quarantine flag"
xattr -cr "$DEST_APP" 2>/dev/null || warn "Couldn't fully clear quarantine attributes; if macOS says the app is damaged, run: xattr -cr \"$DEST_APP\""

# ── Post-install: CrossOver check ────────────────────────────
if [ ! -d "/Applications/CrossOver.app" ]; then
  warn "CrossOver isn't installed."
  info "CrossOver is required to actually play the game. It's a paid app with a 14-day free trial:"
  info "  https://www.codeweavers.com/crossover"
  info "Install it and open it once (it may prompt for Rosetta 2) before launching Lith."
fi

# ── Done ─────────────────────────────────────────────────────
say "Done! Opening Lith Launcher"
info "First launch may sit ~30 seconds with no visible progress while it does a"
info "one-time Windows-environment setup inside CrossOver. That's normal, just let it finish."
open "$DEST_APP" || warn "Couldn't auto-open the app. Open it from $DEST_DIR yourself."

printf '\n\033[1;32mLith Launcher is installed.\033[0m Register an account at https://www.lith.cat/register and log in.\n\n'
