#!/usr/bin/env bash
#
# packages/build.sh — Package each subdirectory into a .pkg archive.
#
# Usage:
#   ./packages/build.sh                   # build all
#   ./packages/build.sh icd-test-runner   # build one
#
# Output: dist/<n>.pkg (zip archives, ready for POST /admin/packages/install)
#
# v0.28.7: Renamed from surfaces/build.sh. Outputs .pkg instead of .surface.
#
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
DIST_DIR="$(cd "$SCRIPT_DIR/.." && pwd)/dist"
mkdir -p "$DIST_DIR"

build_package() {
    local dir="$1"
    local name
    name="$(basename "$dir")"

    if [ ! -f "$dir/manifest.json" ]; then
        echo "  SKIP  $name (no manifest.json)"
        return
    fi

    local version
    version=$(grep -o '"version"[[:space:]]*:[[:space:]]*"[^"]*"' "$dir/manifest.json" | head -1 | sed 's/.*"\([^"]*\)"/\1/')

    local out="$DIST_DIR/${name}.pkg"
    rm -f "$out"

    # Zip whichever standard dirs/files exist alongside manifest.json
    local dirs=""
    [ -d "$dir/js" ]         && dirs="$dirs js/"
    [ -d "$dir/css" ]        && dirs="$dirs css/"
    [ -d "$dir/assets" ]     && dirs="$dirs assets/"
    [ -f "$dir/script.star" ] && dirs="$dirs script.star"
    [ -d "$dir/star" ]        && dirs="$dirs star/"
    [ -d "$dir/migrations" ] && dirs="$dirs migrations/"

    (cd "$dir" && zip -qr "$out" manifest.json $dirs)

    local size
    size=$(du -h "$out" | cut -f1)
    echo "  BUILD $name v${version:-?} → dist/${name}.pkg ($size)"
}

echo "=== Building packages ==="

if [ $# -gt 0 ]; then
    # Build specific package(s)
    for name in "$@"; do
        dir="$SCRIPT_DIR/$name"
        if [ -d "$dir" ]; then
            build_package "$dir"
        else
            echo "  ERROR $name: directory not found at $dir"
            exit 1
        fi
    done
else
    # Build all
    for dir in "$SCRIPT_DIR"/*/; do
        [ -d "$dir" ] || continue
        build_package "$dir"
    done
fi

echo "=== Done ==="
ls -lh "$DIST_DIR"/*.pkg 2>/dev/null || echo "  (no packages built)"
