#! /bin/bash
set -euo pipefail

usage() {
    echo "Usage: $0 <version>"
    echo "Example: $0 0.0.16"
    exit 1
}

if [[ $# -ne 1 ]]; then
    echo "Error: version argument required."
    usage
fi

VERSION="$1"

if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    echo "Error: invalid version format. Expected format: X.Y.Z"
    exit 1
fi

IFS='.' read -r MAJOR MINOR PATCH <<< "$VERSION"

echo "==> Building Voxelverse $VERSION (Major: $MAJOR, Minor: $MINOR, Patch: $PATCH)"

echo "==> Configuring project..."
rm -rf release
cmake "-DCMAKE_GENERATOR=Unix Makefiles" -DCMAKE_CXX_COMPILER=/usr/bin/clang++ -DCMAKE_C_COMPILER=/usr/bin/clang \
    "-DCMAKE_CXX_FLAGS=-DNO_PERF_TIMERS -Wall -Werror -O2 -ggdb -DBUILD_VERSION='{$MAJOR, $MINOR, $PATCH}'" -DCMAKE_C_FLAGS= \
    -DCMAKE_EXPORT_COMPILE_COMMANDS=1 -DCMAKE_BUILD_TYPE=Release -S . -B release

echo "==> Building release..."
cmake --build release -- -j$(nproc)

echo "==> Creating bins package..."
mkdir release/package
cp release/libvoxelverse-engine.so release/package/
cp release/voxelverse-client release/package/
cp release/voxelverse-server release/package/
cp release/voxelverse-devtool release/package/
cp -RT redist release/package
(cd release/package && zip -r ../bins-linux-$VERSION.zip *)

echo "✅ Release package made"