#!/bin/bash
set -eu

script_dir=$(cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd)
build="$script_dir/build"
	
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;

shared_flags="-c -static -msse4.2 -Wno-everything $linker_cmd"

mkdir -p $build

# COMPILER FLAGS
out="-o"

# STB_IMAGE
src="${script_dir}/external/stb/stb.c"
flags="-std=c99 -Iexternal/stb $shared_flags"
obj="${build}/stb.o"
lib="${build}/libstb.a"

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

# CGLTF
src="${script_dir}/external/cgltf/cgltf.c"
flags="-std=c99 -Iexternal/cgltf $shared_flags"
obj="${build}/cgltf.o"
lib="${build}/libcgltf.a"

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

# Build VMA
src="${script_dir}/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 $lib ]; then
	$cpp_compiler $flags $src $out $obj
	ar rcs $lib $obj
	rm $obj
fi

# Convert Shader
shader="${script_dir}/vulkan/convert.comp.glsl"
shader_compiler="glslc"
shader_flags="-std=460 -O --target-env=vulkan1.2"
shader_out="-o${build}/"
shader_stage="-fshader-stage=comp"

base_name=$(basename -- "$shader" .glsl)

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

