#!/usr/bin/env bash
set -euo pipefail

repo="boriemannetje/apex-notes"
asset_name="apex-notes-main-macos-arm64.dmg"
tmp="$(mktemp -d)"
mount="$tmp/mount"

cleanup() {
  hdiutil detach "$mount" >/dev/null 2>&1 || true
  rm -rf "$tmp"
}
trap cleanup EXIT

app_json="$(curl -fsSL "https://raw.githubusercontent.com/$repo/main/package.json")"
current_version="$(printf '%s' "$app_json" | awk -F '"' '$2 == "version" && !found { print $4; found = 1 }')"
test -n "$current_version"

main_json="$(curl -fsSL "https://api.github.com/repos/$repo/commits/main")"
main_sha="$(printf '%s' "$main_json" | awk -F '"' '$2 == "sha" && !found { print $4; found = 1 }')"
test -n "$main_sha"

release_json="$(curl -fsSL "https://api.github.com/repos/$repo/releases/tags/main-production")"
release_sha="$(printf '%s' "$release_json" | awk -F '"' '$2 == "target_commitish" && !found { print $4; found = 1 }')"
test -n "$release_sha"
if [ "$release_sha" != "$main_sha" ]; then
  echo "Apex Notes production is still publishing. Main is $main_sha but the production download is $release_sha, so this installer will not install a stale build." >&2
  exit 1
fi

dmg_url="$(printf '%s' "$release_json" | awk -F '"' -v asset="$asset_name" '$2 == "browser_download_url" && index($4, asset) && !found { print $4; found = 1 }')"
test -n "$dmg_url"

curl -fL --retry 3 -o "$tmp/apex-notes.dmg" "$dmg_url"
hdiutil attach -nobrowse -readonly -mountpoint "$mount" "$tmp/apex-notes.dmg"
codesign --verify --deep --strict "$mount/Apex Notes.app"

sudo rm -rf "/Applications/Apex Notes.app"
sudo ditto "$mount/Apex Notes.app" "/Applications/Apex Notes.app"
codesign --verify --deep --strict "/Applications/Apex Notes.app"
installed_version="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "/Applications/Apex Notes.app/Contents/Info.plist")"
test "$installed_version" = "$current_version"
open "/Applications/Apex Notes.app"
