#!/bin/bash
# Installs Surround One 1.0.0 and its surround audio driver.
#
#   curl -q -fsSL --globoff --proto '=https' --proto-redir '=https' '<this address>' | bash
#
# What it does:
#   1. Checks that this Mac runs macOS 15 or later.
#   2. Downloads the Surround One disk image over HTTPS into a temporary folder.
#   3. Checks the download's SHA-256 against the value published on the download page,
#      and stops if it differs.
#   4. Runs Rotunda.pkg from the disk image with macOS Installer. macOS asks for your
#      password, because the driver goes in /Library/Audio/Plug-Ins/HAL. The app goes
#      in /Applications. Sound stops for a moment while macOS reloads its audio service.
#   5. Ejects the disk image and deletes the temporary folder.
#
# It changes no security settings and installs nothing else.
set -euo pipefail

# shellcheck disable=SC1083
DMG_URL=https://github.com/nurx-me/surround-one/releases/download/v1.0.0/Surround-One-1.0.0.dmg
SHA256=''

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

main() {
  [ "$(uname -s)" = Darwin ] || fail 'Surround One runs on macOS only.'
  local major image actual
  major="$(sw_vers -productVersion | cut -d. -f1)"
  [ "$major" -ge 15 ] || fail "Surround One needs macOS 15 or later. This Mac runs $(sw_vers -productVersion)."

  [[ "$SHA256" =~ ^[a-f0-9]{64}$ ]] || fail 'This installer is not ready for download.'
  if pgrep -x Rotunda >/dev/null; then
    fail 'Turn off and quit the app before installing.'
  fi

  WORK="$(mktemp -d -t rotunda)"
  trap 'hdiutil detach -quiet "$WORK/volume" 2>/dev/null || true; rm -rf "$WORK"' EXIT
  image="$WORK/download.dmg"

  printf 'Downloading Surround One 1.0.0...\n'
  curl -q -fL --proto '=https' --proto-redir '=https' --max-time 300 --progress-bar -o "$image" "$DMG_URL" || fail 'The download failed. Check your connection and try again.'

  actual="$(shasum -a 256 "$image" | cut -d' ' -f1)"
  [ "$actual" = "$SHA256" ] || fail "The download does not match the published SHA-256, so nothing was installed. Expected $SHA256, got $actual."
  printf 'SHA-256 matches: %s\n' "$actual"

  hdiutil attach -quiet -nobrowse -readonly -noautoopen -mountpoint "$WORK/volume" "$image" || fail 'The disk image did not open.'
  [ -f "$WORK/volume/Rotunda.pkg" ] || fail 'The disk image has no Rotunda.pkg.'

  printf 'Installing. macOS asks for your password to install the app and its audio driver.\n'
  sudo /usr/sbin/installer -pkg "$WORK/volume/Rotunda.pkg" -target / || fail 'Installer did not finish.'

  printf '\nSurround One is installed. Open it from Applications: open "/Applications/Rotunda.app"\n'
}

main "$@"
