#!/usr/bin/env bash
#
# Build the distributable plugin zip.
#
# WHY THIS EXISTS
# Until now the repository folder WAS the shipped plugin: whatever sat on disk got zipped and
# sent to customers. That put our test harness on every customer's server - and the tests
# define ABSPATH themselves, which satisfies the `if (!defined('ABSPATH')) exit;` guard in every
# plugin file, so run-tests.php was reachable over HTTP and would execute plugin code outside
# WordPress. It also shipped .git, Composer manifests and developer notes.
#
# Uses `git archive`, so it needs nothing but git, and it ships only COMMITTED files - a release
# can never contain a half-finished local edit. What is left out is listed as export-ignore in
# .gitattributes, which is the single source of truth.
#
# Usage:  ./build.sh              build from HEAD
#         ./build.sh v2.1.11      build from a tag or any ref
#
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SLUG="speedy-go"
REF="${1:-HEAD}"

VERSION="$(git -C "$ROOT" show "$REF:$SLUG.php" | grep -m1 -oE '^Version:[[:space:]]*[0-9][0-9.]*' | tr -d ' ' | cut -d: -f2)"
if [ -z "$VERSION" ]; then
    echo "Could not read Version from $SLUG.php at $REF" >&2
    exit 1
fi

DIST="$ROOT/dist"
ZIP="$DIST/$SLUG-$VERSION.zip"
mkdir -p "$DIST"
rm -f "$ZIP"

git -C "$ROOT" archive --format=zip --prefix="$SLUG/" -o "$ZIP" "$REF"

# A build that silently ships the tests is worse than no build script, because it looks safe.
LEAKED="$(unzip -Z1 "$ZIP" | grep -E "^$SLUG/(tests/|build\.sh|composer\.(json|lock)|probe\.json|\.git)" || true)"
if [ -n "$LEAKED" ]; then
    echo "REFUSING: files marked export-ignore are in the zip:" >&2
    echo "$LEAKED" >&2
    exit 1
fi

echo "Built $ZIP  ($(du -h "$ZIP" | cut -f1), $(unzip -Z1 "$ZIP" | wc -l) files, from $REF)"
echo "No test or build files present."
