#!/usr/bin/env bash
# Construye el instalador autocontenido `duckbrain.phar` y publica su sha256.
# Salida en `dist/` (o $DUCKBRAIN_DIST). Uso: scripts/build-phar
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
OUT="${DUCKBRAIN_DIST:-$ROOT/dist}"
PHAR="$OUT/duckbrain.phar"

mkdir -p "$OUT"

php -d phar.readonly=0 -r '
$root = $argv[1];
$pharPath = $argv[2];
@unlink($pharPath);

$phar = new Phar($pharPath);
$phar->startBuffering();
$phar->setStub("#!/usr/bin/env php\n<?php Phar::mapPhar(\"duckbrain.phar\"); require \"phar://duckbrain.phar/bin/duckbrain\"; __HALT_COMPILER();");

$skip = [".git/", "dist/", "tests/", "openspec/", ".opencode/", "node_modules/"];
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS));
foreach ($iterator as $file) {
    if ($file->isDir()) { continue; }
    $rel = substr($file->getPathname(), strlen($root) + 1);
    foreach ($skip as $prefix) {
        if (str_starts_with($rel, $prefix)) { continue 2; }
    }
    $phar->addFile($file->getPathname(), $rel);
}
$phar->stopBuffering();
echo "built {$pharPath}\n";
' "$ROOT" "$PHAR"

chmod +x "$PHAR"
sha256sum "$PHAR" | awk '{print $1}' > "$PHAR.sha256"
echo "sha256: $(cat "$PHAR.sha256")"
