#!/bin/bash
# JobPass Copilot installer for Mac (Apple Silicon or Intel, macOS 13+).
# Downloads the app from jobpass.in, puts it in Applications and opens it.
set -euo pipefail

APP="JobPass Copilot.app"
# Apple Silicon or Intel: pick the matching build
case "$(uname -m)" in
  arm64) URL="https://www.jobpass.in/updates/JobPass-Copilot-Mac-arm64.dmg" ;;
  x86_64) URL="https://www.jobpass.in/updates/JobPass-Copilot-Mac-x64.dmg" ;;
  *) echo "Sorry, this Mac isn't supported."; exit 1 ;;
esac
if [ "$(sw_vers -productVersion | cut -d. -f1)" -lt 13 ]; then
  echo "Sorry, JobPass Copilot needs macOS 13 or newer."; exit 1
fi

TMP="$(mktemp -d)"
cleanup() {
  if [ -n "${MNT:-}" ]; then hdiutil detach "$MNT" -quiet 2>/dev/null || true; fi
  rm -rf "$TMP"
}
trap cleanup EXIT

echo "Downloading JobPass Copilot..."
curl -fL --progress-bar "$URL" -o "$TMP/JobPass-Copilot.dmg"

# Only install exactly what jobpass.in published (SHA-512 from the update feed)
DMG_NAME="$(basename "$URL")"
EXPECTED="$(curl -fsSL https://www.jobpass.in/updates/latest-mac.yml | awk -v f="$DMG_NAME" '$0 ~ "url: "f"$" {getline; print $2; exit}')"
ACTUAL="$(shasum -a 512 "$TMP/JobPass-Copilot.dmg" | awk '{print $1}' | xxd -r -p | base64)"
if [ -z "$EXPECTED" ] || [ "$ACTUAL" != "$EXPECTED" ]; then
  echo "Download check failed. Please try again."; exit 1
fi

MNT="$(hdiutil attach -nobrowse -readonly "$TMP/JobPass-Copilot.dmg" 2>/dev/null | awk -F'\t' '/\/Volumes\//{print $NF}' | tail -1)"
[ -d "$MNT/$APP" ] || { echo "Download looks broken. Please try again."; exit 1; }

echo "Installing to Applications..."
osascript -e 'tell application id "in.jobpass.copilot" to quit' >/dev/null 2>&1 || true
sleep 1
if [ -d "/Applications/$APP" ]; then mv "/Applications/$APP" "$TMP/old.app"; fi
ditto "$MNT/$APP" "/Applications/$APP"
xattr -dr com.apple.quarantine "/Applications/$APP" 2>/dev/null || true

# macOS keeps the "Screen & System Audio Recording" entry of the previous copy, and it doesn't apply
# to the new one (the app isn't signed by Apple). Clear JobPass's entry so macOS asks fresh, once.
tccutil reset ScreenCapture in.jobpass.copilot >/dev/null 2>&1 || true

echo "Done! Opening JobPass Copilot..."
echo "When you press Start, allow \"Screen & System Audio Recording\" for JobPass Copilot, then reopen the app."
open "/Applications/$APP"
