#!/bin/bash
# Lan House installer: downloads the latest release, verifies its SHA-256 and installs it in /Applications.
# Usage: curl -fsSL https://jpazv.github.io/lanhouse/install.sh | bash
set -euo pipefail

BASE="https://github.com/jpazv/lanhouse/releases/latest/download"
APP="/Applications/Lan House.app"

[ "$(uname -s)" = Darwin ] || { echo "Lan House runs on macOS only." >&2; exit 1; }
[ "$(uname -m)" = arm64 ] || { echo "Lan House needs a Mac with Apple Silicon." >&2; exit 1; }

T="$(mktemp -d)"
cleanup() { [ -n "${VOL:-}" ] && hdiutil detach -quiet "$VOL" 2>/dev/null; rm -rf "$T"; }
trap cleanup EXIT

echo "Downloading Lan House…"
curl -fL --progress-bar -o "$T/LanHouse.dmg" "$BASE/LanHouse.dmg"
curl -fsSL -o "$T/LanHouse.dmg.sha256" "$BASE/LanHouse.dmg.sha256"

echo "Verifying the download…"
(cd "$T" && shasum -a 256 -c LanHouse.dmg.sha256 >/dev/null) || { echo "Checksum mismatch: the download is corrupted or was altered. Nothing was installed." >&2; exit 1; }

VOL="$(hdiutil attach -nobrowse -readonly "$T/LanHouse.dmg" | awk -F'\t' '/\/Volumes\//{print $NF}')"
[ -d "$VOL/Lan House.app" ] || { echo "The disk image does not contain Lan House.app." >&2; exit 1; }

if pgrep -x LanHouse >/dev/null; then
  echo "Closing Lan House…"
  osascript -e 'quit app "Lan House"' 2>/dev/null || true
  for _ in $(seq 20); do pgrep -x LanHouse >/dev/null || break; sleep 0.5; done
  pgrep -x LanHouse >/dev/null && { echo "Quit Lan House and run the installer again." >&2; exit 1; }
fi
echo "Installing to /Applications…"
rm -rf "$APP"
ditto "$VOL/Lan House.app" "$APP"

if ! /usr/bin/arch -x86_64 /usr/bin/true 2>/dev/null; then
  echo "Installing Rosetta 2 (needed to run Windows games)…"
  softwareupdate --install-rosetta --agree-to-license
fi

echo "Done. Opening Lan House."
open "$APP"
