#!/bin/bash
# Installs the MotherDuck add-in for Excel for Mac (Microsoft 365, version 16.35 or later).
#   curl -fsSL https://motherduck.com/labs/excel/install/install-mac.sh | bash
#   curl -fsSL https://motherduck.com/labs/excel/install/install-mac.sh | bash -s -- --uninstall
# It copies the add-in's manifest into Excel's add-in folder and clears Excel's add-in cache.
# Nothing else is installed; the add-in itself runs from https://motherduck.com/labs/excel.
set -euo pipefail
URL="https://motherduck.com/labs/excel"
WEF="$HOME/Library/Containers/com.microsoft.Excel/Data/Documents/wef"
CACHE="$HOME/Library/Containers/com.microsoft.Excel/Data/Library/Caches"
TARGET="$WEF/motherduck-excel-addin.manifest.xml"

if pgrep -x "Microsoft Excel" >/dev/null 2>&1; then
  echo "Excel is open. Quit Excel (Cmd+Q), then run this command again."
  exit 1
fi

if [[ "${1:-}" == "--uninstall" ]]; then
  rm -f "$TARGET"
  rm -rf "${CACHE:?}"/*
  echo "MotherDuck add-in removed. Start Excel again."
  exit 0
fi

mkdir -p "$WEF"
curl -fsSL "$URL/manifest.prod.xml" -o "$TARGET.tmp"
grep -q "<OfficeApp" "$TARGET.tmp" || { echo "Download failed: not a manifest."; rm -f "$TARGET.tmp"; exit 1; }
mv "$TARGET.tmp" "$TARGET"
rm -rf "${CACHE:?}"/*
echo "Installed. Starting Excel: open a workbook, then Home → MotherDuck."
open -a "Microsoft Excel" || true
