#!/usr/bin/env bash
set -euo pipefail

# Run from the project root regardless of where the script is invoked.
cd "$(dirname "$0")"

SERVER_USER="richard"
SERVER_HOST="192.168.1.168"
SERVER_PATH="/opt/bulloseum/data"

BUILD_DIR="build/web"

# Derive the version the same way GameVersion does (single source of truth):
# numeric version from project.godot, pre-release channel from game_version.gd.
VERSION_NUMBER="$(grep -oP 'config/version="\K[^"]+' project.godot)"
CHANNEL="$(grep -oP 'const CHANNEL: String = "\K[^"]*' game_version.gd || true)"
VERSION="v${VERSION_NUMBER}"
[ -n "$CHANNEL" ] && VERSION="${VERSION}-${CHANNEL}"

GIT_COMMIT="$(git rev-parse --short HEAD 2>/dev/null || echo unknown)"
BUILD_DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)"

echo "building Bullosseum ${VERSION} (${GIT_COMMIT})"

mkdir -p "$BUILD_DIR"
godot --headless --export-release "Web" "$BUILD_DIR/index.html"

gzip -kf "$BUILD_DIR/index.wasm"

# Version stamp shipped alongside the flat build so the server records what's live.
cat > "$BUILD_DIR/version.txt" <<EOF
version=${VERSION}
commit=${GIT_COMMIT}
built=${BUILD_DATE}
EOF

scp "$BUILD_DIR/index.html" \
    "$BUILD_DIR/index.js" \
    "$BUILD_DIR/index.wasm.gz" \
    "$BUILD_DIR/index.pck" \
    "$BUILD_DIR/index.audio.worklet.js" \
    "$BUILD_DIR/index.audio.position.worklet.js" \
    "$BUILD_DIR/index.icon.png" \
    "$BUILD_DIR/index.apple-touch-icon.png" \
    "$BUILD_DIR/index.png" \
    "$BUILD_DIR/version.txt" \
    "$SERVER_USER@$SERVER_HOST:$SERVER_PATH/"

echo "deployed ${VERSION} to $SERVER_HOST:$SERVER_PATH"
