#!/usr/bin/env bash
# Build the app on THIS machine and package a ready-to-upload cPanel bundle.
# The cPanel server never compiles anything — its glibc is too old for
# Next.js native (SWC/Turbopack) bindings.
#
# Usage:  npm run package:cpanel
# Output: heavyhaul-agent-cpanel.zip  (upload + extract on the server)
set -euo pipefail
cd "$(dirname "$0")/.."

echo "==> Building (standalone output)…"
STANDALONE=1 npm run build

echo "==> Assembling deploy/ …"
rm -rf deploy
mkdir -p deploy
cp -R .next/standalone/. deploy/
mkdir -p deploy/.next
cp -R .next/static deploy/.next/static
[ -d public ] && cp -R public deploy/public

# Strip platform-specific image binaries: images.unoptimized is set in
# next.config.ts, so sharp is never loaded at runtime.
rm -rf deploy/node_modules/sharp deploy/node_modules/@img

# Sanity check: no native binaries may remain (they'd be Mac-only).
native=$(find deploy -name '*.node' | wc -l | tr -d ' ')
if [ "$native" != "0" ]; then
  echo "ERROR: $native native .node binaries remain in deploy/ — they will not run on Linux:" >&2
  find deploy -name '*.node' >&2
  exit 1
fi

echo "==> Zipping…"
rm -f heavyhaul-agent-cpanel.zip
(cd deploy && zip -qry ../heavyhaul-agent-cpanel.zip .)

echo "==> Done: heavyhaul-agent-cpanel.zip ($(du -h heavyhaul-agent-cpanel.zip | cut -f1 | tr -d ' '))"
echo "    Next steps: see CPANEL_DEPLOY.md"
