#!/bin/bash
# HaloIsland v26.0 — App ZIP installer (Chopsticks HQ pattern)
# Save to disk first, then run. Do not pipe curl | bash.
set -Eeuo pipefail

echo "HaloIsland Installer (App ZIP)"
echo "------------------------------"

[[ "$(uname)" == "Darwin" ]] || { echo "macOS only."; exit 1; }
[[ "${EUID:-$(id -u)}" -ne 0 ]] || { echo "Do not run as root or with sudo."; exit 1; }

VER="26.0"
ZIP_NAME="HaloIsland-26.0-macOS.zip"
URL="https://chopstickshq.com/haloisland/${ZIP_NAME}"
APP_NAME="HaloIsland.app"
DEST="$HOME/Applications/${APP_NAME}"

TMP=$(mktemp -d "${TMPDIR:-/tmp}/haloisland-install.XXXXXX")
trap 'rm -rf -- "$TMP"' EXIT

echo "Downloading ${ZIP_NAME}…"
curl --progress-bar -fL "$URL" -o "$TMP/haloisland.zip" \
  || { echo "Download failed: $URL"; exit 1; }

echo "Unzipping…"
unzip -qo "$TMP/haloisland.zip" -d "$TMP/out"

APP_SRC=""
if [[ -d "${TMP}/out/${APP_NAME}" ]]; then
  APP_SRC="${TMP}/out/${APP_NAME}"
else
  APP_SRC="$(find "$TMP/out" -maxdepth 3 -name "$APP_NAME" -type d | head -1 || true)"
fi
[[ -n "$APP_SRC" && -d "$APP_SRC" ]] || { echo "Archive did not contain ${APP_NAME}"; exit 1; }

echo "Installing to ${DEST}…"
mkdir -p "$HOME/Applications"
rm -rf "$DEST"
ditto "$APP_SRC" "$DEST"
xattr -cr "$DEST" 2>/dev/null || true

echo "✓ Done → ${DEST}"
echo "  HaloIsland v${VER} · open from ~/Applications or Spotlight"
