#!/usr/bin/env bash
#
# Package the Shoe Customizer plugin into an installable zip.
#
#   ./build.sh
#   -> dist/shoe-customizer-<version>.zip   (top-level folder: shoe-customizer/)
#
# Upload that zip via WordPress admin: Plugins -> Add New -> Upload Plugin.
# Version is read from the plugin header so the filename always matches.
#
# Uses `zip` if present, else python3, else php — whichever the machine has.
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SRC="$HERE/shoe-customizer"          # the plugin folder that must sit in wp-content/plugins/
DIST="$HERE/dist"

if [ ! -f "$SRC/shoe-customizer.php" ]; then
	echo "error: $SRC/shoe-customizer.php not found" >&2
	exit 1
fi

VER="$(grep -m1 'Version:' "$SRC/shoe-customizer.php" | sed -E 's/.*Version:[[:space:]]*//' | tr -d '\r' | xargs)"
[ -n "$VER" ] || VER="0.0.0"
OUT="$DIST/shoe-customizer-$VER.zip"

mkdir -p "$DIST"
rm -f "$OUT"

echo "Packaging shoe-customizer v$VER -> $OUT"

if command -v zip >/dev/null 2>&1; then
	( cd "$HERE" && zip -rq "$OUT" shoe-customizer \
		-x '*/.git/*' '*/.DS_Store' '*/dist/*' '*/node_modules/*' )
elif command -v python3 >/dev/null 2>&1; then
	python3 - "$SRC" "$OUT" <<'PY'
import os, sys, zipfile
src, out = sys.argv[1], sys.argv[2]
base = os.path.dirname(src)  # plugin/ ; arcnames become shoe-customizer/...
skip_dirs = {'.git', 'dist', 'node_modules'}
with zipfile.ZipFile(out, 'w', zipfile.ZIP_DEFLATED) as z:
    for root, dirs, files in os.walk(src):
        dirs[:] = [d for d in dirs if d not in skip_dirs]
        for f in sorted(files):
            if f == '.DS_Store':
                continue
            p = os.path.join(root, f)
            z.write(p, os.path.relpath(p, base))
PY
elif command -v php >/dev/null 2>&1; then
	php -r '
		$src = $argv[1]; $out = $argv[2]; $base = dirname($src);
		$z = new ZipArchive();
		$z->open($out, ZipArchive::CREATE | ZipArchive::OVERWRITE);
		$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($src, FilesystemIterator::SKIP_DOTS));
		foreach ($it as $f) {
			$path = $f->getPathname();
			if (strpos($path, "/.git/") !== false || basename($path) === ".DS_Store") continue;
			$z->addFile($path, substr($path, strlen($base) + 1));
		}
		$z->close();
	' "$SRC" "$OUT"
else
	echo "error: need one of zip, python3, or php to build" >&2
	exit 1
fi

echo "Done: $(du -h "$OUT" | cut -f1)  $OUT"
