#!/bin/bash
set -euo pipefail
source "$(dirname "$0")/product.env"
[[ "${3:-/}" == / ]] || { echo 'Install on the current startup disk.' >&2; exit 1; }
[[ "$(uname -m)" == arm64 ]] || { echo 'An Apple Silicon Mac is required.' >&2; exit 1; }
os_version="$(/usr/bin/sw_vers -productVersion)"; os_major="${os_version%%.*}"
(( os_major >= 13 )) || { echo 'macOS 13 or later is required.' >&2; exit 1; }
host_running=0; host_unknown=0
for host in 'Logic Pro' GarageBand; do
  if /usr/bin/pgrep -x "$host" >/dev/null 2>&1; then host_running=1;
  else host_status=$?; [[ "$host_status" == 1 ]] || host_unknown=1; fi
done
if (( host_unknown )); then
  echo 'Cannot inspect running applications; installation stopped before replacing any component.' >&2; exit 1
fi
if (( host_running )); then
  echo 'Close Logic Pro and GarageBand, then run this installer again. No apps were closed.' >&2; exit 1
fi

# A per-user AU with the same identity can mask a system-wide update. Never remove it silently.
for candidate in /Users/*/Library/Audio/Plug-Ins/Components/"$PRODUCT.component"; do
  if [[ -e "$candidate" ]]; then
    printf 'An existing per-user component can hide this update: %s\nUse the included manual installer to update that copy, or back it up and remove it before system-wide installation.\n' "$candidate" >&2
    exit 1
  fi
done
state_dir="/Library/Application Support/Pep Instruments/Installer State/$PRODUCT-$VERSION"
backup_root="/Library/Application Support/Pep Instruments/Backups/$PRODUCT"
umask 077
mkdir -p "$state_dir" "$backup_root"
transaction="$(mktemp -d "$backup_root/pkg-$(date +%Y%m%d-%H%M%S).XXXXXX")"
target="/Library/Audio/Plug-Ins/Components/$PRODUCT.component"
[[ ! -L "$target" ]] || { echo 'Existing component is a symlink; review it before installing.' >&2; exit 1; }
if [[ -e "$target" ]]; then
  /usr/bin/ditto "$target" "$transaction/$PRODUCT.component"
  printf '%s\n' present >"$transaction/previous-state"
else
  printf '%s\n' absent >"$transaction/previous-state"
fi
printf '%s\n' "$transaction" >"$state_dir/transaction"
