#!/usr/bin/env bash
# DeepPerfection - Linux installer
#
# Copies the VST3 and CLAP plugins into the standard Linux plugin folders.
# Run it from the folder it ships in (it installs the plugins sitting next to it).
#
# Usage:
#   ./install.sh                       Install for the current user (no sudo)
#                                      VST3 -> ~/.vst3   CLAP -> ~/.clap
#   ./install.sh --system              Install system-wide (prompts for sudo)
#                                      VST3 -> /usr/lib/vst3   CLAP -> /usr/lib/clap
#   ./install.sh --uninstall           Remove the per-user install
#   ./install.sh --uninstall --system  Remove the system-wide install
#
# After installing, rescan plugins in your DAW.
set -euo pipefail

APP="DeepPerfection"
# Plugins shipped in this release (base names; .vst3 bundle + .clap file each).
PLUGINS=("DeepPerfection" "DeepPerfection MultiTrack Sum" "DeepPerfection MultiTrack Send")
# Resolve the directory this script lives in so it works from any cwd.
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

SYSTEM=0
UNINSTALL=0
for arg in "$@"; do
  case "$arg" in
    --system)    SYSTEM=1 ;;
    --uninstall) UNINSTALL=1 ;;
    -h|--help)   sed -n '2,/^set -euo/{/^set -euo/d;s/^#\{1,\} \{0,1\}//;p;}' "$0"; exit 0 ;;
    *)           echo "Unknown option: $arg (try --help)" >&2; exit 2 ;;
  esac
done

if [ "$SYSTEM" -eq 1 ]; then
  VST3_DIR="/usr/lib/vst3"
  CLAP_DIR="/usr/lib/clap"
  SUDO="sudo"
else
  VST3_DIR="$HOME/.vst3"
  CLAP_DIR="$HOME/.clap"
  SUDO=""
fi

install_one() {
  # $1 = source (file or bundle dir), $2 = destination dir
  local src="$1" dst="$2"
  if [ ! -e "$src" ]; then
    echo "  skip: $(basename "$src") not found next to this script"
    return
  fi
  $SUDO mkdir -p "$dst"
  $SUDO rm -rf "${dst:?}/$(basename "$src")"
  $SUDO cp -R "$src" "$dst/"
  echo "  $(basename "$src") -> $dst/"
}

uninstall_one() {
  # $1 = name, $2 = destination dir
  local name="$1" dst="$2"
  if [ -e "$dst/$name" ]; then
    $SUDO rm -rf "${dst:?}/$name"
    echo "  removed $dst/$name"
  fi
}

if [ "$UNINSTALL" -eq 1 ]; then
  echo "Uninstalling $APP..."
  for p in "${PLUGINS[@]}"; do
    uninstall_one "$p.vst3" "$VST3_DIR"
    uninstall_one "$p.clap" "$CLAP_DIR"
  done
  echo "Done. Rescan plugins in your DAW."
  exit 0
fi

echo "Installing $APP..."
for p in "${PLUGINS[@]}"; do
  install_one "$HERE/$p.vst3" "$VST3_DIR"
  install_one "$HERE/$p.clap" "$CLAP_DIR"
done
echo "Done. Rescan plugins in your DAW."
