#!/bin/bash
set -euo pipefail

product='Surround One'
before_quitting() {
  echo "Before quitting $product, open License and click Deactivate and remove while online to free your seat."
  echo "In $product Settings, turn off Open at Login. Then turn the app off, quit it and choose your speakers or headphones in System Settings > Sound > Output."
}

if [[ "${1:-}" == --dry-run && $# == 1 ]]; then
  before_quitting
  echo "Would check the direct installer receipt and both bundles before removing the app, driver and receipt."
  echo "Shared app data and Keychain records are kept unless you run an explicit cleanup command."
  exit 0
fi

case "$#:${1:-}" in
  0:) scope=system ;;
  1:--remove-user-data) scope=user ;;
  1:--remove-test-and-legacy-licenses) scope=licenses ;;
  *)
    echo "Usage: bash uninstall.sh [--dry-run | --remove-user-data | --remove-test-and-legacy-licenses]" >&2
    exit 2
    ;;
esac
[[ "$(/usr/bin/uname -s)" == Darwin ]] &&
  user_id=$(/usr/bin/id -u) && [[ "$user_id" != 0 ]] ||
  { echo "Run this as the signed-in macOS user." >&2; exit 2; }
before_quitting
if /usr/bin/pgrep -x Rotunda >/dev/null; then
  echo "$product is still running. Quit it and run this again." >&2
  exit 1
elif [[ $? != 1 ]]; then
  echo "Could not check whether $product is running. Nothing was removed." >&2
  exit 1
fi
echo "Local removal does not free your license seat or cancel a subscription. If you cannot deactivate in the app, contact support."
case "$scope" in
  system)
    prompt="Remove the verified direct-download app, driver and installer receipt? Shared app data and Keychain records will be kept."
    ;;
  user)
    prompt="Delete this user's shared app data, login agents, preferences and local production Creem license? Other copies may use this data."
    ;;
  licenses)
    prompt="Delete this user's test Creem and legacy license records from the login keychain? Other copies may use these records."
    ;;
esac
if ! read -r -p "$prompt [y/N] " answer </dev/tty; then
  echo "Run the uninstaller in Terminal so you can confirm removal. Nothing was removed." >&2
  exit 2
fi
[[ "$answer" == y || "$answer" == Y ]] || exit 0

status=0
incomplete() {
  status=1
  printf '%s\n' "$*" >&2
}

receipt=com.rotunda.surround.installer
app=/Applications/Rotunda.app
driver=/Library/Audio/Plug-Ins/HAL/RotundaSurround.driver

bundle_owned_by_receipt() {
  local bundle="$1" info parent
  [[ -d "$bundle" && ! -L "$bundle" && "$(/usr/bin/stat -f %u "$bundle")" == 0 ]] &&
    parent=$(cd -P -- "${bundle%/*}" && pwd -P) && [[ "$parent" == "${bundle%/*}" ]] &&
    info=$(/usr/sbin/pkgutil --file-info-plist "$bundle") &&
    [[ "$(/usr/bin/plutil -extract path raw -expect string -o - - <<< "$info")" == "$bundle" &&
       "$(/usr/bin/plutil -extract path-info raw -expect array -o - - <<< "$info")" == 1 &&
       "$(/usr/bin/plutil -extract path-info.0.pkgid raw -expect string -o - - <<< "$info")" == "$receipt" ]]
}

bundle_value() {
  local plist="$1/Contents/Info.plist"
  [[ ! -L "$1/Contents" && -f "$plist" && ! -L "$plist" ]] &&
    /usr/bin/plutil -extract "$2" raw -expect string -o - "$plist" 2>/dev/null
}

if [[ "$scope" == system ]]; then
  if ! receipts=$(/usr/sbin/pkgutil --pkgs); then
    echo "Could not check installer receipt $receipt. Nothing was removed." >&2
    exit 1
  fi
  if [[ $'\n'"$receipts"$'\n' != *$'\n'"$receipt"$'\n'* ]]; then
    if [[ ! -e "$app" && ! -L "$app" && ! -e "$driver" && ! -L "$driver" ]]; then
      echo "No direct-download installation found. Nothing was removed."
      exit 0
    fi
    echo "No direct installer receipt ($receipt) found. Nothing was removed." >&2
    exit 1
  fi
  for bundle in "$app" "$driver"; do
    [[ -e "$bundle" || -L "$bundle" ]] || continue
    if ! bundle_owned_by_receipt "$bundle" 2>/dev/null; then
      echo "Could not verify that the direct installer owns $bundle. Nothing was removed." >&2
      exit 1
    fi
    bundle_id=$(bundle_value "$bundle" CFBundleIdentifier) || bundle_id=
    if [[ "$bundle" == "$app" ]]; then
      if [[ "$(bundle_value "$bundle" RotundaDistributionChannel)" != direct ||
            -e "$bundle/Contents/_MASReceipt" || -L "$bundle/Contents/_MASReceipt" ||
            ( "$bundle_id" != com.rotunda.surround &&
              ( "$bundle_id" != com.rotunda.surround.distribution-preview ||
                "$(bundle_value "$bundle" RotundaCreemEnvironment)" != test ) ) ]]; then
        echo "$bundle is not a recognized direct-download app. Nothing was removed." >&2
        exit 1
      fi
    elif [[ "$bundle_id" != com.rotunda.surround.driver ]]; then
      echo "$bundle has an unexpected driver bundle identifier. Nothing was removed." >&2
      exit 1
    fi
    set -- "$@" "$bundle"
  done
  # shellcheck disable=SC2024
  if [[ $# != 0 ]] && ! /usr/bin/sudo /bin/rm -rf "$@" </dev/tty; then
    echo "Could not finish removing the direct-download app and driver. The receipt was left alone. Rerun from your signed-in account and approve the administrator prompt." >&2
    exit 1
  fi
  echo "Restart macOS to unload the previous driver."
  # shellcheck disable=SC2024
  if ! /usr/bin/sudo /usr/sbin/pkgutil --forget "$receipt" >/dev/null </dev/tty; then
    echo "Could not remove installer receipt $receipt. Rerun and approve the administrator prompt." >&2
    exit 1
  fi
  echo "$product and its direct-download driver were removed from disk. Shared app data and Keychain records were kept."
  exit 0
fi

if [[ "$scope" == user ]]; then
  for agent in "$HOME"/Library/LaunchAgents/com.rotunda.surround{,.updater}.plist; do
    if [[ -f "$agent" || -L "$agent" ]]; then
      /bin/launchctl bootout "gui/$user_id" "$agent" 2>/dev/null || true
      if ! /bin/rm -f "$agent"; then
        incomplete "Could not remove $agent. In Finder, move only this item to the Trash."
      fi
    fi
  done

  if ! defaults_error=$(LC_ALL=C /usr/bin/defaults delete com.rotunda.surround 2>&1) &&
     [[ "$defaults_error" != *"Domain (com.rotunda.surround) not found."* ]]; then
    incomplete "Could not clear the com.rotunda.surround preferences domain. Rerun after restarting or contact support."
  fi
  preferences="$HOME/Library/Preferences/com.rotunda.surround.plist"
  if ! /bin/rm -f "$preferences"; then
    incomplete "Could not remove $preferences. In Finder, move only this item to the Trash."
  fi
  for path in "$HOME"/Library/Containers/com.rotunda.surround{,.browser} "$HOME/Library/Application Support/Rotunda"; do
    if ! /bin/rm -rf "$path"; then
      incomplete "Could not remove $path. Try moving only this folder to the Trash in Finder. If macOS blocks that too, leave the folder in place and contact support."
    fi
  done
  set -- com.rotunda.surround.licensing.creem.production
  echo "If $product still appears under Open at Login in System Settings > General > Login Items & Extensions, remove it there."
else
  set -- com.rotunda.surround.{licensing,license}.{production,sandbox} com.rotunda.surround.licensing.creem.test
fi

login_keychain="$HOME/Library/Keychains/login.keychain-db"
keychain_item_not_found=44
for service in "$@"; do
  while :; do
    keychain_status=0
    /usr/bin/security delete-generic-password -s "$service" "$login_keychain" >/dev/null 2>&1 || keychain_status=$?
    [[ "$keychain_status" != 0 ]] || continue
    if [[ "$keychain_status" != "$keychain_item_not_found" ]]; then
      incomplete "Could not remove all Keychain items for $service. Unlock your login keychain and rerun, or remove only items with this service in Keychain Access."
    fi
    break
  done
done

if [[ "$status" != 0 ]]; then
  echo "Cleanup incomplete. Follow the steps above, then rerun the same cleanup command." >&2
  exit "$status"
fi
echo "The requested local cleanup is complete. No installed bundles or receipts were removed."
