#!/usr/bin/env bash
# Build the Companion module bundle (.tgz) for OFFLINE import into Bitfocus Companion.
# © 2026 Krometis Analytics.
#
#   bash build-tgz.sh [output-dir]      # default output dir: this folder
#
# Produces  krometis-kuesync-<version>.tgz  rooted at  krometis-kuesync/  WITH the production
# node_modules bundled. Companion's "Import module package" needs BOTH the manifest at
# krometis-kuesync/companion/manifest.json AND the module's dependencies present.
#
# DO NOT use `npm pack` for this: it roots the archive at package/ and STRIPS node_modules, which
# Companion rejects with "Doesn't look like a valid module, missing manifest" (seen live on 0.7.12).
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VERSION="$(node -pe "require('$HERE/package.json').version")"
OUT="$(cd "${1:-$HERE}" && pwd)"

echo "==> Installing production deps"
( cd "$HERE" && npm install --omit=dev --no-audit --no-fund >/dev/null )

TMP="$(mktemp -d)"
STAGE="$TMP/krometis-kuesync"
mkdir -p "$STAGE"
cp -R "$HERE/package.json" "$HERE/companion" "$HERE/src" "$HERE/node_modules" "$STAGE/"
[ -f "$HERE/package-lock.json" ] && cp "$HERE/package-lock.json" "$STAGE/"
find "$STAGE" -name '.DS_Store' -delete 2>/dev/null || true

TGZ="$OUT/krometis-kuesync-$VERSION.tgz"
rm -f "$TGZ"
tar czf "$TGZ" -C "$TMP" krometis-kuesync
rm -rf "$TMP"

# Sanity: manifest must be at the rooted path, node_modules must be bundled. Capture the listing ONCE
# (piping `tar | grep -q` under `set -o pipefail` makes tar die with SIGPIPE and falsely "fail").
LIST="$(tar tzf "$TGZ")"
printf '%s\n' "$LIST" | grep -q '^krometis-kuesync/companion/manifest.json$' \
  || { echo "ERROR: manifest missing from tgz" >&2; exit 1; }
printf '%s\n' "$LIST" | grep -q '^krometis-kuesync/node_modules/@companion-module/base/package.json$' \
  || { echo "ERROR: node_modules not bundled" >&2; exit 1; }
echo "built $TGZ  (v$VERSION, $(printf '%s\n' "$LIST" | wc -l | tr -d ' ') files)"
