#!/usr/bin/env bash
#
# Tape DSP — Linux installer (offline). Installs Tape DSP Machine + Echo +
# Compressor (VST3 + LV2) from the plugin payload shipped alongside this script
# (tape-dsp-linux-payload.tar.gz in the same folder). No network needed. Works
# on any distro; re-run any time to reinstall/upgrade.
#
#   Per-user (default):   ./install.sh
#   System-wide:          sudo ./install.sh --system
#   Uninstall:            ./install.sh --uninstall
set -euo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
PAYLOAD="$HERE/tape-dsp-linux-payload.tar.gz"

MODE="user"; ACTION="install"
for arg in "$@"; do
  case "$arg" in
    --system) MODE="system";;
    --uninstall) ACTION="uninstall";;
    -h|--help) echo "Usage: install.sh [--system] [--uninstall]"; exit 0;;
  esac
done

if [ "$MODE" = "system" ]; then
  VST3_DEST="/usr/lib/vst3"; LV2_DEST="/usr/lib/lv2"
else
  VST3_DEST="$HOME/.vst3"; LV2_DEST="$HOME/.lv2"
fi

NAMES=("Tape DSP Machine" "Tape DSP Echo" "Tape DSP Compressor")

if [ "$ACTION" = "uninstall" ]; then
  for n in "${NAMES[@]}"; do
    rm -rf "$VST3_DEST/$n.vst3" "$LV2_DEST/$n.lv2"
  done
  echo "Tape DSP: removed."
  exit 0
fi

command -v tar >/dev/null 2>&1 || { echo "tar is required." >&2; exit 1; }
[ -f "$PAYLOAD" ] || { echo "Plugin payload not found next to this script: $PAYLOAD" >&2; exit 1; }

TMP="$(mktemp -d /tmp/tapedsp-install.XXXXXX)"
trap 'rm -rf "$TMP"' EXIT

echo "Tape DSP: installing bundled plugins…"
tar -xzf "$PAYLOAD" -C "$TMP"

mkdir -p "$VST3_DEST" "$LV2_DEST"

install_from() {
  local srcdir="$1" dest="$2" glob="$3"
  [ -d "$srcdir" ] || return 0
  shopt -s nullglob
  for bundle in "$srcdir"/$glob; do
    local name; name="$(basename "$bundle")"
    echo "Tape DSP: installing $name → $dest"
    rm -rf "$dest/$name"
    cp -R "$bundle" "$dest/"
  done
  shopt -u nullglob
}

install_from "$TMP/vst3" "$VST3_DEST" "*.vst3"
install_from "$TMP/lv2"  "$LV2_DEST"  "*.lv2"

echo "Tape DSP: installation complete."
