#!/bin/bash
set -eu

if [ -z "$1" ]; then
	echo "No output parameter named, please pass the build directory to this script."
	exit 1
fi

script_dir=$(cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd)
build="$1"

mkdir -p $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;

# COMPILER FLAGS
out="-o"

# STB_IMAGE
src="${script_dir}/external/stb/stb.c"
flags="-std=c99 -Wno-everything -Iexternal/stb -c -static"
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

# M3D
#src="${script_dir}/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

# CGLM
src="${script_dir}/external/cglm/cglm.c"
flags="-std=c99 -Wno-everything -Iexternal/cglm -c -static"
obj="${build}/cglm.o"
lib="${build}/libcglm.a"

if ! [ -f "${build}/libcglm.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 -Wno-everything -Iexternal/cgltf -c -static"
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
