#!/usr/bin/env bash
# Shared Tape DSP Linux uninstall logic (per-user + system plugin folders).
set -u

HERE="$(cd "$(dirname "$0")" && pwd)"
NAMES_FILE="$HERE/tape-dsp-uninstall-names.sh"
if [ -f "$NAMES_FILE" ]; then
  # shellcheck source=/dev/null
  source "$NAMES_FILE"
elif [ -f "$HERE/../../pack-products.sh" ]; then
  # Development-tree fallback.
  # shellcheck source=../../pack-products.sh
  source "$HERE/../../pack-products.sh"
  TAPE_DSP_PLUGIN_NAMES=("${TAPE_PACK_DISPLAY_NAMES[@]}")
else
  echo "Uninstaller error: plugin name manifest missing." >&2
  exit 1
fi

tape_dsp_remove_from_dirs() {
  local vst3="$1" lv2="$2"
  for n in "${TAPE_DSP_PLUGIN_NAMES[@]}"; do
    rm -rf "$vst3/$n.vst3" "$lv2/$n.lv2" 2>/dev/null || true
  done
}

tape_dsp_remove_user_plugins() {
  tape_dsp_remove_from_dirs "$HOME/.vst3" "$HOME/.lv2"
}

tape_dsp_remove_system_plugins() {
  tape_dsp_remove_from_dirs /usr/lib/vst3 /usr/lib/lv2
}

tape_dsp_remove_app_folder() {
  rm -rf "$HOME/.local/share/Tape DSP" 2>/dev/null || true
  rm -rf /opt/Tape\ DSP 2>/dev/null || true
  rm -rf /usr/share/Tape\ DSP 2>/dev/null || true
}

tape_dsp_forget_deb_package() {
  if command -v dpkg >/dev/null 2>&1 && dpkg -l tape-dsp >/dev/null 2>&1; then
    if [ "$(id -u)" = 0 ]; then
      dpkg -r tape-dsp >/dev/null 2>&1 || true
    elif command -v pkexec >/dev/null 2>&1; then
      pkexec dpkg -r tape-dsp >/dev/null 2>&1 || true
    elif command -v sudo >/dev/null 2>&1; then
      sudo dpkg -r tape-dsp >/dev/null 2>&1 || true
    fi
  fi
}
