#!/usr/bin/env bash
# Builds a release tarball with all artifacts pre-built.
# The Pi just untars, runs bun install, and starts.
#
# Usage: bun run release
# Output: dist/toes-<version>.tar.gz
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

VERSION=$(grep '"version"' package.json | head -1 | sed 's/.*"version": *"\(.*\)".*/\1/')
STAGING="$ROOT/dist/toes-$VERSION"

echo ">> Building toes $VERSION release"

# ── Clean ────────────────────────────────────────────────

rm -rf dist
mkdir -p dist

# ── Client bundle ────────────────────────────────────────

echo ">> Building client bundle"
rm -rf pub/client
mkdir -p pub/client
bun build src/client/index.tsx \
  --outfile pub/client/index.js \
  --target browser \
  --minify

# ── Embedded templates ───────────────────────────────────

echo ">> Embedding templates"
bun run scripts/embed-templates.ts

# ── Bare repos ───────────────────────────────────────────

echo ">> Building bundled app repos"
bash scripts/build-repos.sh

# ── CLI binary (linux-arm64 for Pi) ──────────────────────

echo ">> Building CLI for linux-arm64"
bun build src/cli/index.ts \
  --compile \
  --target bun-linux-arm64 \
  --minify \
  --sourcemap=external \
  --define="__GIT_SHA__=\"$VERSION\"" \
  --outfile dist/toes-linux-arm64

# ── Stage release ────────────────────────────────────────

echo ">> Staging release"
mkdir -p "$STAGING"

# Source (excluding dev artifacts)
COPYFILE_DISABLE=1 tar -C "$ROOT" \
  --no-xattrs \
  --exclude='node_modules' \
  --exclude='.git' \
  --exclude='dist' \
  --exclude='apps/*/node_modules' \
  --exclude='apps/*/logs' \
  --exclude='apps/*/current' \
  --exclude='apps/*/[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9]' \
  -cf - . | tar -C "$STAGING" -xf -

# Pre-built artifacts
mkdir -p "$STAGING/pub" "$STAGING/dist"
cp -a pub/client "$STAGING/pub/client"
cp -a dist/repos "$STAGING/dist/repos"
cp dist/toes-linux-arm64 "$STAGING/dist/toes"

# Generated templates (so the server doesn't need to generate them)
cp src/lib/templates.data.ts "$STAGING/src/lib/templates.data.ts"

# ── Tarball ──────────────────────────────────────────────

echo ">> Creating tarball"
COPYFILE_DISABLE=1 tar -C dist --no-xattrs -czf "dist/toes-$VERSION.tar.gz" "toes-$VERSION"
rm -rf "$STAGING"

SIZE=$(du -h "dist/toes-$VERSION.tar.gz" | cut -f1)
echo ">> dist/toes-$VERSION.tar.gz ($SIZE)"
