#!/bin/sh
# Installs getcta, the teleprompter under your MacBook notch.
#
#   curl -fsSL https://getcta.store/install.sh | sh
#
# Downloads the latest release for this Mac, puts it in Applications (or
# ~/Applications without write access there), and opens it. Running it again
# updates getcta. Source of every build: github.com/nikhil008-git/getcta-releases
#
# The whole script is a function called on the last line, so a download cut
# off halfway runs nothing.

main() {
  set -eu
  repo="nikhil008-git/getcta-releases"

  [ "$(uname -s)" = "Darwin" ] || fail "getcta is a Mac app."

  arch="$(uname -m)"
  # A shell running under Rosetta reports x86_64 on Apple silicon.
  if [ "$arch" = "x86_64" ] && [ "$(sysctl -in sysctl.proc_translated 2>/dev/null || true)" = "1" ]; then
    arch="arm64"
  fi
  case "$arch" in
    arm64) asset="getcta-arm64-mac.zip" ;;
    x86_64) asset="getcta-x64-mac.zip" ;;
    *) fail "this Mac ($arch) isn't supported." ;;
  esac

  major="$(sw_vers -productVersion | cut -d. -f1)"
  [ "$major" -ge 13 ] || fail "getcta needs macOS 13 Ventura or later."

  tmp="$(mktemp -d)"
  trap 'rm -rf "$tmp"' EXIT INT TERM

  say "Downloading getcta..."
  curl -fL --progress-bar -o "$tmp/getcta.zip" "https://github.com/$repo/releases/latest/download/$asset" \
    || fail "the download failed. Check your connection and run the command again."
  ditto -x -k "$tmp/getcta.zip" "$tmp" || fail "the download was damaged. Run the command again."
  [ -d "$tmp/getcta.app" ] || fail "the download didn't contain getcta."

  dest="/Applications"
  if [ ! -w "$dest" ]; then
    dest="$HOME/Applications"
    mkdir -p "$dest"
  fi

  if pgrep -xq getcta; then
    say "Quitting the running getcta..."
    osascript -e 'tell application id "store.getcta.app" to quit' >/dev/null 2>&1 || true
    i=0
    while pgrep -xq getcta && [ "$i" -lt 20 ]; do
      sleep 0.5
      i=$((i + 1))
    done
  fi

  rm -rf "$dest/getcta.app" || fail "couldn't replace $dest/getcta.app. Quit getcta and run the command again."
  mv "$tmp/getcta.app" "$dest/getcta.app"
  xattr -dr com.apple.quarantine "$dest/getcta.app" 2>/dev/null || true

  version="$(defaults read "$dest/getcta.app/Contents/Info" CFBundleShortVersionString 2>/dev/null || true)"
  say "Installed getcta ${version} in $dest."
  open "$dest/getcta.app"
  say "getcta is opening. Updates arrive inside the app from now on."
}

say() { printf '%s\n' "$*"; }
fail() {
  printf 'getcta: %s\n' "$*" >&2
  exit 1
}

main "$@"
