#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SRC_PLUGIN="$SCRIPT_DIR/MindfulLensFilmEngineDemo.lrplugin"
TARGET_DIR="$HOME/Library/Application Support/Adobe/Lightroom/Modules"
TARGET_PLUGIN="$TARGET_DIR/MindfulLensFilmEngineDemo.lrplugin"

printf '\nAnalog Signature Demo Installer (macOS)\n'
printf '=================================\n\n'

if [[ ! -d "$SRC_PLUGIN" ]]; then
  echo "ERROR: Missing plugin folder next to installer:"
  echo "  $SRC_PLUGIN"
  echo "Extract the demo ZIP and run this installer again."
  exit 1
fi

if pgrep -x "Adobe Lightroom Classic" >/dev/null 2>&1; then
  echo "WARNING: Lightroom Classic appears to be running."
  echo "Please close Lightroom before continuing."
  exit 1
fi

mkdir -p "$TARGET_DIR"

if [[ -d "$TARGET_PLUGIN" ]]; then
  rm -rf "$TARGET_PLUGIN"
fi

cp -R "$SRC_PLUGIN" "$TARGET_PLUGIN"

xattr -dr com.apple.quarantine "$TARGET_PLUGIN" 2>/dev/null || true
find "$TARGET_PLUGIN" \( -name '._*' -o -name '.DS_Store' \) -delete 2>/dev/null || true

echo "OK: Plugin installed to:"
echo "  $TARGET_PLUGIN"
echo

if grep -q 'FilmEngineMenu.lua' "$TARGET_PLUGIN/Info.lua" 2>/dev/null; then
  echo "ERROR: Installed plugin Info.lua still registers legacy 9-panel UI."
  exit 1
fi
if ! grep -q 'com.mindfullens.filmengine.demo' "$TARGET_PLUGIN/Info.lua" 2>/dev/null; then
  echo "ERROR: Wrong toolkit ID (expected com.mindfullens.filmengine.demo)."
  exit 1
fi
MENU_COUNT=$(grep -c 'AnalogSignaturePanelOneMenu.lua' "$TARGET_PLUGIN/Info.lua" 2>/dev/null || echo 0)
if [[ "$MENU_COUNT" -ne 1 ]]; then
  echo "ERROR: Expected exactly one customer panel menu in Info.lua."
  exit 1
fi
BUILD_LINE=$(grep -E 'build\s*=\s*[0-9]+' "$TARGET_PLUGIN/Info.lua" 2>/dev/null | head -1 || true)
if ! echo "$BUILD_LINE" | grep -q 'build = 187'; then
  echo "ERROR: Expected build 187 in Info.lua. Found: $BUILD_LINE"
  exit 1
fi

echo "Verified: demo toolkit, build 187, one-panel Info.lua"
echo
echo "Next steps:"
echo "1) Open Lightroom Classic"
echo "2) File -> Plug-in Manager -> Add..."
echo "3) Select MindfulLensFilmEngineDemo.lrplugin and click Reload Plug-in"
