#!/bin/bash
# Removes Knobpilot from this Mac. Double-click it in Finder, or run it in Terminal.
# Your DAW projects keep the rack's saved settings; they come back if Knobpilot is installed again.
# With --all it also removes your Knobpilot data: rack presets, plugin cards, logs and the saved sign-in.
set -u

ALL=0
[ "${1:-}" = "--all" ] && ALL=1

echo "This removes the Knobpilot Audio Unit, VST3 and app from this Mac."
[ $ALL = 1 ] && echo "It also removes your rack presets, plugin cards, logs and saved sign-in (--all)."
echo "Close your DAW first."
read -r -p "Continue? [y/N] " answer
case "$answer" in [yY]*) ;; *) echo "Nothing removed."; exit 0 ;; esac

SYSTEM=("/Library/Audio/Plug-Ins/Components/Knobpilot.component"
        "/Library/Audio/Plug-Ins/VST3/Knobpilot.vst3"
        "/Applications/Knobpilot.app")
# Copies a development build may have put in the user's own plugin folders.
USER_COPIES=("$HOME/Library/Audio/Plug-Ins/Components/Knobpilot.component"
             "$HOME/Library/Audio/Plug-Ins/VST3/Knobpilot.vst3")

# The plugin and the app come out first. If they do not, nothing else is touched: your presets and
# sign-in stay, and the message says so, so a cancelled password prompt never ends in "removed".
incomplete() {
  echo "Knobpilot is NOT fully removed: $1"
  echo "Your presets, plugin cards and sign-in were left alone. Close your DAW and run this again."
  exit 1
}
echo "macOS asks for your password to remove the system-wide plugins."
sudo /bin/rm -rf "${SYSTEM[@]}" || incomplete "the system-wide plugins and app could not be removed (password cancelled or refused)."
/bin/rm -rf "${USER_COPIES[@]}" || incomplete "the copies in your own plugin folders could not be removed."
for path in "${SYSTEM[@]}" "${USER_COPIES[@]}"; do
  [ -e "$path" ] && incomplete "$path is still there."
done
sudo /usr/sbin/pkgutil --forget com.knobpilot.pkg >/dev/null 2>&1 || true

if [ $ALL = 1 ]; then
  /bin/rm -rf "$HOME/Library/Application Support/Knobpilot" "$HOME/Library/Logs/Knobpilot"
  # A build that kept the sign-in in the Keychain (signed builds; earlier betas).
  /usr/bin/security delete-generic-password -s com.knobpilot.account >/dev/null 2>&1 || true
fi

# The Audio Unit registry forgets the plugin on its next scan.
/usr/bin/killall -9 AudioComponentRegistrar >/dev/null 2>&1 || true
echo "Knobpilot is removed."
