#!/usr/bin/env bash
# GTM Tools browser extension installer.
#   curl -fsSL https://api.gtm-tools.sh/extension/install.sh | bash
# Downloads the latest build into a stable folder (~/GTM Tools/extension)
# so you Load-unpacked once and every future run reuses the same path. No Node,
# no dependencies beyond curl + unzip (preinstalled on macOS/Linux).
set -euo pipefail

BASE="${GTM_TOOLS_BASE_URL:-https://api.gtm-tools.sh}"
# Stable, easy-to-find install path — sits at the root of $HOME under a properly
# named folder ("GTM Tools") so it's instantly recognizable in Finder pickers.
DEST="${GTM_TOOLS_DIR:-$HOME/GTM Tools/extension}"
URL="$BASE/extension/chrome-mv3-prod.zip"

command -v curl >/dev/null  || { echo "error: curl is required" >&2; exit 1; }
command -v unzip >/dev/null || { echo "error: unzip is required" >&2; exit 1; }

first_time=1
[ -d "$DEST" ] && first_time=0

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT

echo "Downloading the GTM Tools extension…"
curl -fsSL "$URL" -o "$tmp/ext.zip"

rm -rf "$DEST"
mkdir -p "$DEST"
unzip -q "$tmp/ext.zip" -d "$DEST"

echo ""
if [ "$first_time" -eq 1 ]; then
  echo "✓ Installed at  $DEST"
  echo ""
  # Copy the path to the clipboard so the fastest route (⌘⇧G → paste) is one
  # gesture. Falls back gracefully if pbcopy isn't available.
  clipboard_note=""
  if command -v pbcopy >/dev/null 2>&1; then
    printf "%s" "$DEST" | pbcopy
    clipboard_note=" (path is already in your clipboard)"
  fi
  echo "Load it in your browser (once — the path never changes):"
  echo "  1. Open  chrome://extensions"
  echo "  2. Turn on  Developer mode  (top-right)"
  echo "  3. Click  Load unpacked  and select this folder:"
  echo ""
  echo "         $DEST"
  echo ""
  echo "       Fastest:  press  ⌘⇧G  → paste (⌘V) → Return → Select${clipboard_note}"
  echo "       Or browse:  your home folder → GTM Tools → extension"
  echo "  4. Click the GTM Tools icon and press  Connect"
else
  echo "✓ Updated at  $DEST"
  echo ""
  echo "Apply it: open  chrome://extensions  and click the reload icon on the"
  echo "GTM Tools card (or just restart the browser)."
fi
echo ""
