#!/usr/bin/env bash
# Build dist/avtoambor-deploy.zip — a self-contained Windows 7 bundle.
#
# The bundle's node_modules/better-sqlite3 ships a native binary for
# win32-x64 + Node 16 (ABI v93), fetched via prebuild-install. The local
# dev tree (../node_modules/) is never touched, so `make run` / `npm run
# dev` keep working with the Linux binary.

set -euo pipefail

cd "$(dirname "$0")/.."
ROOT="$(pwd)"
DIST="$ROOT/dist"
STAGE="$DIST/avtoambor"
ZIP="$DIST/avtoambor-deploy.zip"
NODE_VERSION="16.20.2"
NODE_ABI="93"

# Sanity: we need Node 16 active so the build matches the runtime target.
NODE_MAJOR="$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)"
if [ "$NODE_MAJOR" != "16" ]; then
  echo "make-bundle.sh: Node 16 must be active (got $(node --version 2>/dev/null || echo none))."
  echo "  run: nvm use   (reads .nvmrc → 16.20.2)"
  exit 1
fi

for cmd in npm zip rsync; do
  command -v "$cmd" >/dev/null || { echo "make-bundle.sh: missing required tool: $cmd"; exit 1; }
done

echo "==> Building production output (vite build)"
npm run build

echo "==> Preparing staging directory: $STAGE"
rm -rf "$DIST"
mkdir -p "$STAGE"

echo "==> Installing production dependencies into staging"
cp package.json package-lock.json "$STAGE/"
( cd "$STAGE" && npm ci --omit=dev --no-audit --no-fund )

echo "==> Swapping better-sqlite3 native binary → win32-x64 / node v$NODE_ABI"
BS3="$STAGE/node_modules/better-sqlite3"
[ -d "$BS3" ] || { echo "make-bundle.sh: better-sqlite3 not present in staging"; exit 1; }
(
  cd "$BS3"
  # Remove the Linux binary that npm just installed; prebuild-install would
  # otherwise skip the download believing the binary is already in place.
  rm -rf build/Release
  npx --no-install prebuild-install \
    --runtime=node \
    --target="v$NODE_VERSION" \
    --platform=win32 \
    --arch=x64 \
    --verbose
)
# Confirm the swap landed.
if [ ! -f "$BS3/build/Release/better_sqlite3.node" ]; then
  echo "make-bundle.sh: prebuild-install did not produce build/Release/better_sqlite3.node"
  exit 1
fi
echo "    binary: $(file "$BS3/build/Release/better_sqlite3.node" | cut -d: -f2-)"

echo "==> Copying app files into staging"
rsync -a --delete build/ "$STAGE/build/"
mkdir -p "$STAGE/scripts"
cp scripts/init-db.js "$STAGE/scripts/"
mkdir -p "$STAGE/src/lib/server"
cp src/lib/server/schema.sql src/lib/server/seed.sql "$STAGE/src/lib/server/"
mkdir -p "$STAGE/data" "$STAGE/backups"

echo "==> Copying deploy/ assets to the bundle root (double-click access)"
# README, .bat launchers, MSI installers — all at the top level of the zip.
cp deploy/install.bat deploy/start.bat deploy/backup.bat "$STAGE/"
cp deploy/README.md "$STAGE/"
cp deploy/node-v16.20.2-x64.msi "$STAGE/"
cp deploy/node-v16.20.2-x86.msi "$STAGE/"

echo "==> Creating zip: $ZIP"
( cd "$DIST" && zip -rq "$(basename "$ZIP")" "$(basename "$STAGE")" )

ZIP_SIZE="$(du -h "$ZIP" | cut -f1)"
echo
echo "Bundle ready:"
echo "  $ZIP  ($ZIP_SIZE)"
