#!/bin/bash
# Bouwt alle downloads: Node-pakketten (.zip/.tar.gz) + standalone binaries per platform.
# Vereist: bun (https://bun.sh) voor de standalone binaries.
set -e
APP=/var/www/vhosts/p33k.nl/modelrailpro
WEBROOT=/var/www/vhosts/modelrailpro.com/httpdocs
DL="$WEBROOT/dl"
BUN="${BUN:-$HOME/.bun/bin/bun}"
OWNER=modelrailpro
cd "$APP"
rm -f data/license.json

# Versienummer hard in de code zetten (uit package.json) zodat ook de standalone het kent.
VER=$(node -e "process.stdout.write(require('./package.json').version)")
printf "'use strict';\n// Door de build gegenereerd uit package.json.\nmodule.exports = '%s';\n" "$VER" > lib/version.js
echo "→ versie $VER ingebakken (lib/version.js)"

# oude versie-bestanden opruimen (houd alleen de huidige + stabiele namen)
rm -f "$DL"/modelrailpro-* "$DL"/modelrailpro-[0-9]*.zip "$DL"/modelrailpro-[0-9]*.tar.gz "$DL"/standalone/modelrailpro-* "$DL"/standalone/modelrailpro-[0-9]*.zip 2>/dev/null || true

echo "→ Node-pakketten (v$VER)…"
tar --exclude='node_modules' --exclude='data/license.json' --exclude='.git' --exclude='tools/license-gen.js' \
    -czf "$DL/modelrailpro-$VER.tar.gz" -C /var/www/vhosts/p33k.nl modelrailpro
( cd /var/www/vhosts/p33k.nl && rm -f "$DL/modelrailpro-$VER.zip" && \
  zip -rq "$DL/modelrailpro-$VER.zip" modelrailpro -x "modelrailpro/node_modules/*" "modelrailpro/data/license.json" "modelrailpro/.git/*" "modelrailpro/tools/license-gen.js" )
# stabiele namen (altijd = nieuwste), zodat oude links blijven werken
cp -f "$DL/modelrailpro-$VER.zip" "$DL/modelrailpro.zip"
cp -f "$DL/modelrailpro-$VER.tar.gz" "$DL/modelrailpro.tar.gz"

# Webversie (relay) op p33k.nl publiceren: kopie van de public-assets.
APP_WEB="$WEBROOT/app"
mkdir -p "$APP_WEB"
cp -f public/*.html public/*.js public/*.css public/*.webmanifest public/*.svg "$APP_WEB"/ 2>/dev/null || true
chown -R "$OWNER":psacln "$APP_WEB" 2>/dev/null || true
echo "→ webversie bijgewerkt ($APP_WEB)"

echo "→ Standalone binaries…"
DIST=$(mktemp -d)
declare -A T=([windows-x64]=bun-windows-x64 [mac-applesilicon]=bun-darwin-arm64 [mac-intel]=bun-darwin-x64 [linux-x64]=bun-linux-x64 [raspberrypi-arm64]=bun-linux-arm64)
mkdir -p "$DL/standalone"
for name in "${!T[@]}"; do
  out="$DIST/modelrailpro-$name"; mkdir -p "$out"
  ext=""; [ "$name" = "windows-x64" ] && ext=".exe"
  "$BUN" build ./server.js --compile --target=${T[$name]} --outfile "$out/modelrailpro$ext" >/dev/null 2>&1
  cp -r public data "$out/"
  ( cd "$DIST" && rm -f "$DL/standalone/modelrailpro-$VER-$name.zip" && zip -rq "$DL/standalone/modelrailpro-$VER-$name.zip" "modelrailpro-$name"
    cp -f "$DL/standalone/modelrailpro-$VER-$name.zip" "$DL/standalone/modelrailpro-$name.zip" )  # stabiele naam = nieuwste
  echo "   ✓ $name (v$VER)"
done
rm -rf "$DIST"
chown -R "$OWNER":psacln "$DL" 2>/dev/null || true
echo "Klaar. Vergeet version.json niet bij te werken (zie RELEASE.md)."
