#!/bin/bash
set -euo pipefail

# Installer supplies the selected target volume as argument 3. Only these two
# exact product bundles may be backed up or replaced. Never close the host.
VOLUME="${3%/}"
BACKUP_BASE="$VOLUME/Library/Application Support/VIRATRONIK/Spectrum/Backups"
STAMP="$(date -u +%Y%m%d-%H%M%S)-$$"
for RELATIVE in \
  'Library/Audio/Plug-Ins/VST3/VIRATRONIK Spectrum.vst3' \
  'Library/Audio/Plug-Ins/Components/VIRATRONIK Spectrum.component'; do
  BUNDLE="$VOLUME/$RELATIVE"
  BINARY="$BUNDLE/Contents/MacOS/VIRATRONIK Spectrum"
  if [[ -f "$BINARY" ]] && /usr/sbin/lsof -t "$BINARY" >/dev/null 2>&1; then
    echo "Guarda tu sesion y cierra el DAW: VIRATRONIK SPECTRONIC (Spectrum) esta cargado." >&2
    exit 1
  fi
done
for RELATIVE in \
  'Library/Audio/Plug-Ins/VST3/VIRATRONIK Spectrum.vst3' \
  'Library/Audio/Plug-Ins/Components/VIRATRONIK Spectrum.component'; do
  BUNDLE="$VOLUME/$RELATIVE"
  if [[ -d "$BUNDLE" ]]; then
    mkdir -p "$BACKUP_BASE/$STAMP"
    /usr/bin/ditto "$BUNDLE" "$BACKUP_BASE/$STAMP/$(basename "$BUNDLE")"
  fi
done
