#!/bin/bash
# Firetool installer for macOS (https://firetool.in).
# The download page gives you this line with your own download link (it works for 15 minutes):
#   curl -fsSL https://firetool.in/install-mac.sh | bash -s -- '<download link>' '<SHA-256>'
#
# Why a Terminal command: Firetool isn't notarized by Apple yet. A zip downloaded in a browser is marked as
# "from the internet", and macOS then calls the app damaged. Downloaded with curl it isn't marked. This script checks
# the file's SHA-256, installs the app in Applications, gives it the local (ad-hoc) signature macOS needs to start it,
# and opens it. It sends nothing anywhere except the download itself.
set -euo pipefail

url="${1:-}"; sha="${2:-}"
say() { printf '%s\n' "$*"; }
stop() { say ""; say "Firetool wasn't installed: $*"; exit 1; }

[ "$(uname -s)" = "Darwin" ] || stop "this installer is for macOS."
case "$url" in
  https://storage.googleapis.com/firestudio-61405.firebasestorage.app/releases/Firetool-*-macos-*.zip\?*) ;;
  *) stop "use the command from https://firetool.in/download. It includes your own download link." ;;
esac
case "$url" in *-macos-arm64.zip\?*) want="arm64" ;; *) want="x86_64" ;; esac
have="$(uname -m)"
if [ "$want" = "arm64" ] && [ "$have" != "arm64" ]; then
  stop "that's the Apple Silicon build, and this Mac has an Intel processor. On the download page, choose \"Mac with an Intel processor\"."
fi
if [ "$want" = "x86_64" ] && [ "$have" = "arm64" ]; then
  say "Note: this is the Intel build. It runs on this Mac through Rosetta; the Apple Silicon build is faster."
fi

tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT
say "Downloading Firetool..."
curl -fL --progress-bar -o "$tmp/Firetool.zip" "$url" \
  || stop "the download failed. Download links work for 15 minutes: get a new one from the download page."
if [ -n "$sha" ]; then
  got="$(shasum -a 256 "$tmp/Firetool.zip" | awk '{print $1}')"
  [ "$got" = "$sha" ] || stop "the download doesn't match its SHA-256 checksum."
  say "Checksum matches."
fi

ditto -x -k "$tmp/Firetool.zip" "$tmp/files"
app="$(find "$tmp/files" -maxdepth 2 -type d -name 'Firetool.app' | head -n 1)"
[ -n "$app" ] || stop "the download didn't contain Firetool.app."

DEST="/Applications"; [ -w "$DEST" ] || DEST="$HOME/Applications"
mkdir -p "$DEST"
say "Installing in $DEST..."
rm -rf "$DEST/Firetool.app"
ditto "$app" "$DEST/Firetool.app"
xattr -cr "$DEST/Firetool.app" 2>/dev/null || true
codesign --force --deep --sign - "$DEST/Firetool.app" >/dev/null 2>&1 \
  || codesign --force --deep --sign - "$DEST/Firetool.app"

# The same app under its earlier name (its settings, keys and schedules carry on in Firetool)
rm -rf "$DEST/Firestore Studio.app"

say "Done. Opening Firetool."
open "$DEST/Firetool.app"
