#!/bin/bash
set -eu

# SHADERS

shader_compiler="glslc"
shader_flags="--target-spv=spv1.6 -std=460"
shader_out="-oassets/shaders/"

mkdir -p assets/shaders

for shader in src/shaders/*.glsl; do
	base_name=$(basename -- "$shader" .glsl)

	case "$base_name" in
		*.vert) shader_stage="-fshader-stage=vert" ;;
		*.frag) shader_stage="-fshader-stage=frag" ;;
		*.tesc) shader_stage="-fshader-stage=tesc" ;;
		*.tese) shader_stage="-fshader-stage=tese" ;;
		*.geom) shader_stage="-fshader-stage=geom" ;;
		*.comp) shader_stage="-fshader-stage=comp" ;;
		*) continue ;;
	esac

	$shader_compiler $shader_flags $shader_stage $shader "${shader_out}${base_name}.spv"
done

if 	 [ -x "$(command -v g++)" ]; 		then cpp_compiler="g++"; c_compiler="gcc";
elif [ -x "$(command -v clang++)" ]; then cpp_compiler="clang++"; c_compiler="clang";
else echo "Unable to find c++ cpp_compiler"; exit -1; fi;

if 	 [ -x "$(command -v mold)" ]; then linker_cmd="-fuse-ld=mold"; 
elif [ -x "$(command -v lld)"  ]; then linker_cmd="-fuse-ld=lld";
elif [ -x "$(command -v ld)"   ]; then linker_cmd="-fuse-ld=ld"; 
else echo "Unable to find c/c++ linker"; exit -1; fi;

# VMA
src="external/vma/vma.cpp"
flags="-std=c++20 -D_USE_MATH_DEFINES -Iexternal/vma -c -Wno-everything -static"
out="-o"
obj="build/vma.o"
lib="build/libvma.a"

if ! [ -f build/libvma.a ]; then
	$cpp_compiler $flags $src $out $obj
	ar rcs $lib $obj
	rm $obj
fi

# XXHASH
src="external/xxhash/xxhash.c"
flags="-std=c99 -Wno-everything -Iexternal/xxhash -c -static"
obj="build/xxhash.o"
lib="build/libxxhash.a"

if ! [ -f build/libxxhash.a ]; then
	$c_compiler $flags $src $out $obj
	ar rcs $lib $obj
	rm $obj
fi

# STB_IMAGE
src="external/stb/stb_image.c"
flags="-std=c99 -Wno-everything -Iexternal/stb -c -static"
obj="build/stb_image.o"
lib="build/libstb_image.a"

if ! [ -f build/libstb_image.a ]; then
	$c_compiler $flags $src $out $obj
	ar rcs $lib $obj
	rm $obj
fi

# M3D
src="external/m3d/m3d.c"
flags="-std=c99 -Wno-everything -Iexternal/m3d -c -static"
obj="build/m3d.o"
lib="build/libm3d.a"

if ! [ -f build/libm3d.a ]; then
	$c_compiler $flags $src $out $obj
	ar rcs $lib $obj
	rm $obj
fi
