#!/bin/bash
# Mix Checker plugin installer — macOS (Apple Silicon + Intel, universal)
#
# After downloading this file, run it from Terminal:
#   1. Open Terminal (Applications > Utilities > Terminal)
#   2. Type:  bash        (with a trailing space)
#   3. Drag this file onto the Terminal window, then press Return
#
# It downloads the plugin and copies it straight into your plugin folders — no
# installer package. Running it this way shows no Gatekeeper prompt (bash reading
# a script is not a gated launch, and the plugin itself is fetched without the
# quarantine flag a browser download would add).
set -euo pipefail

DOWNLOAD_URL="https://mixchecker.in/downloads/MixChecker-macOS.zip"
VST3_DIR="$HOME/Library/Audio/Plug-Ins/VST3"
AU_DIR="$HOME/Library/Audio/Plug-Ins/Components"

say()  { printf '%s\n' "$*"; }
fail() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }

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

say "Mix Checker plugin installer"
say "============================="
say ""
say "Downloading Mix Checker..."
curl -fL --progress-bar "$DOWNLOAD_URL" -o "$TMP/MixChecker-macOS.zip" \
  || fail "download failed — check your internet connection"
unzip -tq "$TMP/MixChecker-macOS.zip" >/dev/null || fail "downloaded file is corrupted — please try again"
unzip -q "$TMP/MixChecker-macOS.zip" -d "$TMP"

VST3_SRC="$(/usr/bin/find "$TMP" -maxdepth 3 -type d -name 'MixChecker.vst3' | head -n 1)"
AU_SRC="$(/usr/bin/find "$TMP" -maxdepth 3 -type d -name 'MixChecker.component' | head -n 1)"
[ -n "$VST3_SRC" ] || fail "downloaded archive did not contain MixChecker.vst3"

mkdir -p "$VST3_DIR" "$AU_DIR"

# Replace any existing install so an old version never lingers alongside the new one.
say "Installing (replacing any previous version)..."
rm -rf "$VST3_DIR/MixChecker.vst3"
cp -R "$VST3_SRC" "$VST3_DIR/"
if [ -n "$AU_SRC" ]; then
  rm -rf "$AU_DIR/MixChecker.component"
  cp -R "$AU_SRC" "$AU_DIR/"
fi

# Belt-and-suspenders: clear any quarantine flag so the DAW never shows a Gatekeeper
# prompt when it loads the plugin.
xattr -cr "$VST3_DIR/MixChecker.vst3" 2>/dev/null || true
[ -n "$AU_SRC" ] && xattr -cr "$AU_DIR/MixChecker.component" 2>/dev/null || true

# An old system-wide copy would shadow this fresh per-user install — flag it.
for OLD in "/Library/Audio/Plug-Ins/VST3/MixChecker.vst3" "/Library/Audio/Plug-Ins/Components/MixChecker.component"; do
  if [ -e "$OLD" ]; then
    say ""
    say "Note: found an older system-wide copy at $OLD"
    say "Remove it so your DAW loads the new version:  sudo rm -rf \"$OLD\""
  fi
done

[ -d "$VST3_DIR/MixChecker.vst3" ] || fail "install verification failed"

say ""
say "Done. Mix Checker is installed:"
say "  VST3: $VST3_DIR/MixChecker.vst3"
[ -n "$AU_SRC" ] && say "  AU:   $AU_DIR/MixChecker.component"
say ""
say "Next: open your DAW, rescan plugins, add Mix Checker LAST on the master channel,"
say "then scan the QR code with the Mix Checker Android app."
