#!/bin/bash
# ZapTicket installer: https://zapticket.bjorken.email
#
#   curl -fsSL https://zapticket.bjorken.email/install.sh | bash
#
# What it does, in order:
#   1. Downloads ZapTicket.app.zip and its .sha256 from the latest GitHub release
#      (github.com/nikbjorken/zapticket) over HTTPS.
#   2. Checks the SHA-256, that the app is ZapTicket (bundle id) and that its code
#      signature is intact. Stops if anything doesn't match.
#   3. Quits ZapTicket if it's running, installs the new copy in /Applications
#      (or ~/Applications if that isn't writable) and opens it.
#
# Files downloaded with curl aren't marked as "downloaded from the internet", so
# macOS doesn't show the "Not Opened" dialog for this unnotarized build.
# No sudo, no password, nothing outside the app folder is touched.
#
# Options (environment variables):
#   ZT_INSTALL_DIR=<folder>   install somewhere else
#   ZT_INSTALL_NO_OPEN=1      don't quit a running copy or open the new one

set -euo pipefail

# Everything is inside main(), which only runs once the whole script has been
# downloaded, so a dropped connection can't run half an installer.
main() {
  local repo="nikbjorken/zapticket"
  local base="${ZT_INSTALL_BASE:-https://github.com/$repo/releases/latest/download}"
  local bundle_id="app.zapticket.ZapTicket"
  local curl_opts=(--fail --silent --show-error --location --retry 2)
  [[ "$base" == https://* ]] && curl_opts+=(--proto '=https' --tlsv1.2)

  bold() { printf '\033[1m%s\033[0m\n' "$*"; }
  step() { printf '  \033[38;5;214m→\033[0m %s\n' "$*"; }
  die()  { printf '\n  \033[31m✗ %s\033[0m\n\n' "$*" >&2; exit 1; }

  echo
  bold "⚡ Installing ZapTicket"

  # --- Checks ------------------------------------------------------------------
  [[ "$(uname -s)" == "Darwin" ]] || die "ZapTicket is a macOS app."
  local major; major="$(sw_vers -productVersion | cut -d. -f1)"
  (( major >= 14 )) || die "ZapTicket needs macOS 14 or later (this Mac has $(sw_vers -productVersion))."

  local dest="${ZT_INSTALL_DIR:-}"
  if [[ -z "$dest" ]]; then
    if [[ -w /Applications ]]; then dest="/Applications"; else dest="$HOME/Applications"; fi
  fi
  mkdir -p "$dest" || die "Can't create $dest."
  [[ -w "$dest" ]] || die "Can't write to $dest."
  local target="$dest/ZapTicket.app"
  if [[ -e "$target" && ! -w "$target" ]]; then
    die "$target exists but isn't writable by you. Remove it in Finder, then run this again."
  fi

  local tmp; tmp="$(mktemp -d)"
  # Expand the path now: the trap runs after main() returns, when $tmp is out of scope.
  trap "rm -rf '$tmp'" EXIT

  # --- Download ----------------------------------------------------------------
  step "Downloading the latest release from GitHub"
  curl "${curl_opts[@]}" -o "$tmp/ZapTicket.app.zip" "$base/ZapTicket.app.zip" \
    || die "Download failed. Check your connection and try again."
  curl "${curl_opts[@]}" -o "$tmp/ZapTicket.app.zip.sha256" "$base/ZapTicket.app.zip.sha256" \
    || die "Couldn't download the checksum, so the app can't be verified."

  # --- Verify ------------------------------------------------------------------
  step "Verifying the download"
  local expected actual
  expected="$(grep -Eo '[0-9a-fA-F]{64}' "$tmp/ZapTicket.app.zip.sha256" | head -1 | tr 'A-F' 'a-f')"
  [[ -n "$expected" ]] || die "The published checksum is unreadable."
  actual="$(shasum -a 256 "$tmp/ZapTicket.app.zip" | cut -d' ' -f1)"
  [[ "$actual" == "$expected" ]] || die "The download doesn't match the published checksum. Nothing was installed."

  ditto -x -k "$tmp/ZapTicket.app.zip" "$tmp/unpacked" || die "Couldn't unpack the download."
  local app="$tmp/unpacked/ZapTicket.app"
  [[ -d "$app" ]] || die "The download doesn't contain ZapTicket.app."
  local got_id version
  got_id="$(/usr/libexec/PlistBuddy -c 'Print CFBundleIdentifier' "$app/Contents/Info.plist" 2>/dev/null || true)"
  [[ "$got_id" == "$bundle_id" ]] || die "The download isn't ZapTicket ($got_id). Nothing was installed."
  version="$(/usr/libexec/PlistBuddy -c 'Print CFBundleShortVersionString' "$app/Contents/Info.plist" 2>/dev/null || echo '?')"
  codesign --verify --deep --strict "$app" 2>/dev/null || die "The app's code signature is broken. Nothing was installed."
  xattr -dr com.apple.quarantine "$app" 2>/dev/null || true

  # --- Install -----------------------------------------------------------------
  if [[ -z "${ZT_INSTALL_NO_OPEN:-}" ]] && pgrep -x ZapTicket >/dev/null 2>&1; then
    step "Quitting the running copy"
    osascript -e "quit app id \"$bundle_id\"" >/dev/null 2>&1 || true
    for _ in $(seq 1 30); do pgrep -x ZapTicket >/dev/null 2>&1 || break; sleep 0.2; done
    pgrep -x ZapTicket >/dev/null 2>&1 && die "ZapTicket is still running. Quit it from the ⚡ menu, then run this again."
  fi

  step "Installing ZapTicket $version in $dest"
  if [[ -e "$target" ]]; then
    mv "$target" "$tmp/previous.app" || die "Couldn't move the old copy out of the way."
  fi
  if ! mv "$app" "$target"; then
    [[ -e "$tmp/previous.app" ]] && mv "$tmp/previous.app" "$target"
    die "Couldn't install into $dest. Your previous copy was put back."
  fi

  if [[ -z "${ZT_INSTALL_NO_OPEN:-}" ]]; then
    step "Opening ZapTicket"
    open "$target" || true
  fi

  echo
  bold "✓ ZapTicket $version is installed in $dest"
  echo "  Click the ⚡ in your menu bar to connect YouTrack, then press Left ⇧ + Right ⇧."
  echo "  Future updates install from inside the app."
  echo
}

main "$@"
