#!/usr/bin/env bash
# Build a "mail it to someone" fat bundle of the thoughtframe-eclipse plugin,
# packaged as a dropins/ directory zip for another Eclipse.
#
# Usage: eclipse/make-dist.sh [output-dir]      (default: build/dist)
# Produces: <output-dir>/thoughtframe-eclipse_<version>.zip
#
# The bundle is dir-form (not a jar) on purpose: EngineIsland resolves engine/ and
# webapp/ with FileLocator.toFileURL, which needs them to stay real directories.
set -euo pipefail

here="$(cd "$(dirname "$0")" && pwd)"     # .../eclipse
root="$(cd "$here/.." && pwd)"            # repo root
out="${1:-$root/build/dist}"

version="$(grep -E '^Bundle-Version:' "$here/META-INF/MANIFEST.MF" | awk '{print $2}')"
base="${version%.qualifier}"
version="${VERSION:-$base.$(date -u +%Y%m%d%H%M)}"
bundle="thoughtframe-eclipse_${version}"

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

dest="$stage/$bundle"
mkdir -p "$dest"

echo "staging $dest"
cp -r "$here/META-INF" "$dest/"
cp    "$here/plugin.xml" "$dest/"
cp -r "$here/bin/." "$dest/"             # compiled classes at the bundle root
cp -r "$here/lib"    "$dest/"
cp -r "$here/engine" "$dest/"
cp -r "$here/webapp" "$dest/"

# Pin the version (drop .qualifier) so the dropins dir name matches the manifest.
sed -i "s/^Bundle-Version:.*/Bundle-Version: ${version}/" "$dest/META-INF/MANIFEST.MF"

# Runtime node data (the live OpenSearch index) is machine state, not app content - and it
# may be mid-write while the engine is running. Exclude it unless INCLUDE_INDEX=1 (which is
# how you'd carry the frames + notes to another machine, ideally with the engine stopped).
if [ "${INCLUDE_INDEX:-}" != "1" ]; then
  rm -rf "$dest/webapp/WEB-INF/opensearch" "$dest/webapp/WEB-INF/elastic"
  echo "  (excluded webapp/WEB-INF/opensearch (+ legacy elastic) - fresh index on first boot; INCLUDE_INDEX=1 to carry it)"
fi

cat > "$dest/INSTALL.txt" <<EOF
thoughtframe-eclipse ${version} - dropins install
=================================================
1. Unzip this folder into <eclipse>/dropins/
   (you should end up with <eclipse>/dropins/${bundle}/plugin.xml ...)
2. Start Eclipse with -clean once.
3. The plugin self-starts the engine at workbench startup and writes
   ~/.thoughtframe/instances/*.json (ephemeral port).
Requires: an Eclipse with JDT + EGit + M2E (the Require-Bundle list) and a Java 25 runtime.
EOF

mkdir -p "$out"
( cd "$stage" && zip -rq "$out/$bundle.zip" "$bundle" )
echo "wrote $out/$bundle.zip"
ls -lh "$out/$bundle.zip"
