#!/bin/sh
set -e

pushd "$(dirname $0)" > /dev/null

if [[ ! -d "build" ]];
then
	mkdir "build"
fi

pushd "build" > /dev/null

release=0
deps=0
assets=0

for a in $*
do
	let $a=1
done

if [[ ! -d "deps" ]]
then
	deps=1
fi

if [[ ! -d "assets" ]]
then
	assets=1
fi

if [[ $deps == 1 ]]
then
	# We don't build SDL3 like on windows, this assumes you have it installed instead. We can't
	# just ship with the version of SDL3 we want because the shared object system is bad
	echo "[Building dependencies]"

	rm    -rf "deps"
	mkdir -p  "deps/stb"

	cp ../thirdparty/stb/*.h deps/stb
fi

if [[ $assets == 1 ]]
then
	echo "[Copying assets]"

	cp -r "../assets" .
fi

echo "[Building shaders]"

[[ ! -d "assets/shaders" ]] && mkdir "assets/shaders"

glslangValidator -o "assets/shaders/basic.vert.spv" --target-env "vulkan1.3" "../code/vulkan/shaders/basic.vert"
glslangValidator -o "assets/shaders/basic.frag.spv" --target-env "vulkan1.3" "../code/vulkan/shaders/basic.frag"

echo "[Building source]"

COMPILER_OPTS="-Wall -Wno-override-init-side-effects -Wno-missing-braces -Wno-unused-function -Ideps/stb -I../code"
LINKER_OPTS="-lSDL3 -lm"

if [[ $release == 1 ]]
then
	echo "[Release build]"
	gcc -O2 -Werror $COMPILER_OPTS -DLD_RELEASE=1 $(realpath "../code/first.c") -o "ludum" $LINKER_OPTS
else
	echo "[Debug build]"
	gcc -O0 -g -ggdb $COMPILER_OPTS $(realpath "../code/first.c") -o "ldebug" $LINKER_OPTS
fi
