#!/usr/bin/env bash
# Clean House installer
#   curl -fsSL https://cleanhouse-0ax.pages.dev/install.sh | bash
#
# Downloads Clean-House.dmg, checks its SHA-256 against version.json, copies
# Clean House.app to /Applications (or ~/Applications) and opens it. Files
# fetched with curl aren't quarantined, so macOS shows no "can't be opened"
# dialog. Read this script before running it; it's short.
set -euo pipefail

SITE="${CLEANHOUSE_SITE:-https://cleanhouse-0ax.pages.dev}"
APP_NAME="Clean House.app"
BUNDLE_ID="app.macscope.preview"
PROC="MacScope"

bold=$'\033[1m'; dim=$'\033[2m'; blue=$'\033[36m'; red=$'\033[31m'; reset=$'\033[0m'
say()  { printf '%s\n' "${blue}▍${reset} $*"; }
fail() { printf '%s\n' "${red}✗ $*${reset}" >&2; exit 1; }

[[ "$(uname -s)" == "Darwin" ]] || fail "Clean House is a Mac app."
major="$(sw_vers -productVersion | cut -d. -f1)"
(( major >= 15 )) || fail "Needs macOS 15 Sequoia or later (you have $(sw_vers -productVersion))."

tmp="$(mktemp -d)"
mnt=""
cleanup() { [[ -n "$mnt" ]] && hdiutil detach "$mnt" -quiet >/dev/null 2>&1 || true; rm -rf "$tmp"; }
trap cleanup EXIT

say "Checking latest version…"
curl -fsSL "$SITE/version.json" -o "$tmp/version.json" || fail "Couldn't reach $SITE"
field() { plutil -extract "$1" raw -o - "$tmp/version.json" 2>/dev/null || true; }
version="$(field version)"
dmg_url="$(field dmg)"
expected_sha="$(field sha256)"
[[ -n "$dmg_url" ]] || dmg_url="$SITE/download/Clean-House.dmg"
[[ "$dmg_url" == https://* ]] || fail "Refusing non-HTTPS download: $dmg_url"

say "Downloading Clean House ${version:-latest}…"
curl -fL --progress-bar "$dmg_url" -o "$tmp/Clean-House.dmg" || fail "Download failed."

if [[ -n "$expected_sha" ]]; then
  actual_sha="$(shasum -a 256 "$tmp/Clean-House.dmg" | awk '{print $1}')"
  [[ "$actual_sha" == "$expected_sha" ]] || fail "Checksum mismatch, not installing. Expected $expected_sha, got $actual_sha."
  say "Checksum OK."
fi

mnt="$tmp/mnt"; mkdir -p "$mnt"
hdiutil attach "$tmp/Clean-House.dmg" -nobrowse -readonly -quiet -mountpoint "$mnt" || fail "Couldn't open the disk image."
[[ -d "$mnt/$APP_NAME" ]] || fail "Disk image didn't contain $APP_NAME."

dest="/Applications"
[[ -w "$dest" ]] || { dest="$HOME/Applications"; mkdir -p "$dest"; }

if pgrep -xq "$PROC"; then
  say "Quitting running Clean House…"
  osascript -e "quit app id \"$BUNDLE_ID\"" >/dev/null 2>&1 || true
  for _ in 1 2 3 4 5 6 7 8 9 10; do pgrep -xq "$PROC" || break; sleep 0.3; done
fi

rm -rf "${dest:?}/$APP_NAME"
ditto "$mnt/$APP_NAME" "$dest/$APP_NAME"
xattr -dr com.apple.quarantine "$dest/$APP_NAME" 2>/dev/null || true

say "Installed to ${bold}$dest/$APP_NAME${reset}"
open "$dest/$APP_NAME"
printf '%s\n' "" "  ${bold}Every file gets a Why?${reset} Nothing is deleted, only moved to the Trash." \
  "  ${dim}Uninstall: rm -rf \"$dest/$APP_NAME\"${reset}" ""
