#!/bin/bash
# Raids Timer setup assistant. The person approves. This downloads, unpacks, and opens the app.
set -euo pipefail

URL="https://savemypet-backend.onrender.com/raids-timer/downloads/RaidsTimer-Mac.zip"
DEST="$HOME/Applications"
ZIP="$HOME/Downloads/RaidsTimer-Mac.zip"
MIN_BYTES=200000000

osascript <<'APPLESCRIPT' || exit 0
display dialog "Raids Timer will download and open on this Mac.

Click OK to approve. If the Mac asks again, click Open.

Leave the app open so the clock keeps running." buttons {"Cancel", "OK"} default button "OK" with title "Raids Timer"
APPLESCRIPT

mkdir -p "$DEST"
mkdir -p "$HOME/Downloads"

need=1
if [[ -f "$ZIP" ]]; then
  size=$(stat -f%z "$ZIP" 2>/dev/null || echo 0)
  if [[ "$size" -ge "$MIN_BYTES" ]]; then
    need=0
  fi
fi

if [[ "$need" -eq 1 ]]; then
  echo "Downloading Raids Timer…"
  if ! curl -fL --retry 3 --retry-delay 2 -o "$ZIP.partial" "$URL"; then
    rm -f "$ZIP.partial"
    osascript -e 'display dialog "The download did not finish. Check the internet connection and try the Mac download again." buttons {"OK"} with title "Raids Timer"'
    exit 1
  fi
  mv -f "$ZIP.partial" "$ZIP"
fi

echo "Unpacking…"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
unzip -q -o "$ZIP" -d "$TMP"
APP="$TMP/Raids Timer.app"
if [[ ! -d "$APP" ]]; then
  echo "The download did not include Raids Timer."
  osascript -e 'display dialog "The download did not include Raids Timer. Try the Mac download again." buttons {"OK"} with title "Raids Timer"'
  exit 1
fi

xattr -dr com.apple.quarantine "$APP" 2>/dev/null || true
rm -rf "$DEST/Raids Timer.app"
ditto "$APP" "$DEST/Raids Timer.app"
xattr -dr com.apple.quarantine "$DEST/Raids Timer.app" 2>/dev/null || true

echo "Opening Raids Timer…"
if open "$DEST/Raids Timer.app"; then
  osascript <<'APPLESCRIPT'
display dialog "Raids Timer is opening.

If the Mac shows one more message, click Open.
Allow notifications if it asks.
Leave Raids Timer open so the clock keeps running." buttons {"OK"} default button "OK" with title "Raids Timer"
APPLESCRIPT
else
  open "x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Security" >/dev/null 2>&1 || open "x-apple.systempreferences:com.apple.preference.security?General" >/dev/null 2>&1 || true
  osascript <<'APPLESCRIPT'
display dialog "The Mac wants one approval.

System Settings is open. Scroll to the bottom of Privacy & Security and click Open Anyway." buttons {"OK"} default button "OK" with title "Raids Timer"
APPLESCRIPT
fi