#!/usr/bin/env bash
# Concatenate game sources into build/game.js, same pattern as raytracer / frameworkv3.
# Also copies the PHP API into build/ so a local `php -S` and the FTP deploy
# serve the same tree. data/config.php and any sqlite are NEVER copied.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BUILD_FILE="$ROOT/build/game.js"
SRC_DIR="$ROOT/src"

mkdir -p "$ROOT/build"

printf "Build started, output file: %s\n" "$BUILD_FILE"
rm -f "$BUILD_FILE"

FILES=(
	"$SRC_DIR/rng.js"
	"$SRC_DIR/i18n.js"
	"$SRC_DIR/planet.js"
	"$SRC_DIR/blocks.js"
	"$SRC_DIR/easing.js"
	"$SRC_DIR/gameCore.js"
	"$SRC_DIR/flameFx.js"
	"$SRC_DIR/miniLayout.js"
	"$SRC_DIR/miniPredict.js"
	"$SRC_DIR/online.js"
	"$SRC_DIR/offline.js"
	"$SRC_DIR/reward.js"
	"$SRC_DIR/designer.js"
	"$SRC_DIR/loginPrompt.js"
	"$SRC_DIR/main.js"
)

{
	printf '%s\n' "/*"
	printf '%s\n' " * AUTO-GENERATED FILE — DO NOT EDIT BY HAND."
	printf '%s\n' " * Built by src/build.sh from the sources in src/."
	printf '%s\n' " */"
	printf '%s' "var PLANET_CATALOG = "
	cat "$ROOT/server/lib/planets.json"
	printf ';\n'
	printf '%s' "var BLOCK_REGISTRY = "
	cat "$ROOT/server/lib/blocks.json"
	printf ';\n'
	printf '%s' "var I18N_CATALOG = "
	cat "$ROOT/server/lib/i18n.json"
	printf ';\n'
} >> "$BUILD_FILE"

for file in "${FILES[@]}"
do
	if [[ ! -f "$file" ]]
	then
		printf "Missing source file: %s\n" "$file" >&2
		exit 1
	fi
	printf "\n/*\n * Start File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"
	printf "Building %s\n" "$file"
	cat "$file" >> "$BUILD_FILE"
	printf "\n/*\n * End File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"
done

# PHP API lives next to the static game so api.php, auth.php and callback.php
# share a cookie path. Never copy secrets or the database.
SERVER="$ROOT/server"
cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \
	"$SERVER/logout.php" "$SERVER/router.php" "$SERVER/.htaccess" \
	"$ROOT/build/"
mkdir -p "$ROOT/build/lib"
cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" \
	"$SERVER/lib/Planets.php" "$SERVER/lib/planets.json" \
	"$SERVER/lib/Blocks.php" "$SERVER/lib/blocks.json" \
	"$SERVER/lib/i18n.json" "$SERVER/lib/I18n.php" \
	"$ROOT/build/lib/"
mkdir -p "$ROOT/build/data"
cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"
# Belt and braces: a leftover local config or db must never enter build/.
rm -f "$ROOT/build/data/config.php" "$ROOT/build/data/config.lock"
rm -f "$ROOT/build/data/"*.sqlite "$ROOT/build/data/"*.sqlite-journal
rm -rf "$ROOT/build/data/sessions"

printf "DONE\n"
