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

if [ $# -lt 1 ]; then
    echo "Usage: $0 <program> [args...]"
    exit 1
fi

# Default mode is dev unless explicitly user
MODE="${VOXELVERSE_MODE:-dev}"

PROGRAM="$1"
shift

# Build first
cmake --build build -- -j"$(nproc)"

# Run
cd build

export LD_LIBRARY_PATH=.
export VOXELVERSE_ASSETS_DIR=../assets
export VOXELVERSE_DEV=1

if [ "$MODE" != "user" ]; then
    export VOXELVERSE_DEV=1
else
    unset VOXELVERSE_DEV
fi

exec gdb \
    -q \
    -batch \
    --return-child-result \
    -ex "set pagination off" \
    -ex "set logging file gdb.log" \
    -ex "set logging overwrite on" \
    -ex "set logging on" \
    -ex "handle SIGINT nostop noprint pass" \
    -ex "handle SIGPIPE nostop noprint pass" \
    -ex "handle SIGSEGV stop print nopass" \
    -ex "handle SIGABRT stop print nopass" \
    -ex "handle SIGILL stop print nopass" \
    -ex "handle SIGFPE stop print nopass" \
    -ex "run" \
    -ex "bt full" \
    -ex "quit" \
    --args "./voxelverse-$PROGRAM" "$@"
