#!/usr/bin/env bash
# Stage linux-x64 payload (app + embedded Node 20) for .deb or USB folder install.
set -euo pipefail

VERSION="${1:-2.0.0}"
ARCH="${2:-linux-x64}"
NODE_VERSION="${NODE_VERSION:-20.19.5}"

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
PAYLOAD_DIR="${PAYLOAD_DIR:-$ROOT/dist/release/payload/$ARCH}"
APP_DIR="$PAYLOAD_DIR/app"
RUNTIME_DIR="$PAYLOAD_DIR/runtime"
NODE_TARBALL="node-v${NODE_VERSION}-linux-x64.tar.xz"
NODE_URL="https://nodejs.org/dist/v${NODE_VERSION}/${NODE_TARBALL}"

echo "Building payload v$VERSION ($ARCH) -> $PAYLOAD_DIR"

rm -rf "$PAYLOAD_DIR"
mkdir -p "$APP_DIR" "$RUNTIME_DIR"

EXCLUDE=(node_modules .git dist test)
shopt -s dotglob
for item in "$ROOT"/*; do
  name="$(basename "$item")"
  skip=0
  for ex in "${EXCLUDE[@]}"; do
    [[ "$name" == "$ex" ]] && skip=1 && break
  done
  [[ $skip -eq 1 ]] && continue
  cp -a "$item" "$APP_DIR/"
done
shopt -u dotglob

(cd "$APP_DIR" && npm ci --omit=dev)

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
curl -fsSL "$NODE_URL" -o "$TMP/$NODE_TARBALL"
tar -xJf "$TMP/$NODE_TARBALL" -C "$TMP"
cp "$TMP/node-v${NODE_VERSION}-linux-x64/bin/node" "$RUNTIME_DIR/node"
chmod +x "$RUNTIME_DIR/node"

cat >"$PAYLOAD_DIR/payload-manifest.json" <<EOF
{
  "version": "$VERSION",
  "arch": "$ARCH",
  "nodeVersion": "$NODE_VERSION",
  "builtAt": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "gitSha": "${GITHUB_SHA:-}"
}
EOF

echo "Payload ready: app=$APP_DIR runtime=$RUNTIME_DIR/node"
