#!/bin/bash

mkdir -p build

declare -a shared_src=(
	dlib/package.d
	dlib/platform.d
	dlib/fonts.d
	dlib/aliases.d
	dlib/math.d
	dlib/util.d
	dlib/alloc.d
	dlib/assets.d
	dlib/externdecl.d
	dlib/stb_truetype.d
)

d_compiler="ldc"
# Arch ldc-git AUR package (can remove post ldc v1.42)
if [ -x "$(command -v ldc-git)" ]; then
	d_compiler="ldc-git"
fi

if [ "$1" == "wasm" ]; then
	out="build/dlib.wasm"
	declare -a flags=(
		-vgc
		-betterC
		-mtriple=wasm32-unknown-unknown-wasm
		-d-version=DLIB_TEST
		-fvisibility=hidden
		--unittest
		-Iwasm/runtime
		-i=core
		-i=std
		-i=.
		--real-precision=double
		--Xcc=-DBUILD_WASM
		-gcc=clang
		"--of=$out"
	)
	declare -a wasm_src=(
		wasm/runtime/object.d
		opengl/opengl_wasm.d
		opengl/opengl.d
		opengl/glenum.d
	)

	$d_compiler "${flags[@]}" "${shared_src[@]}" "${wasm_src[@]}"

	cp $out wasm/dlib.wasm
else
	out="build/Test_Runner"
	declare -a native_src=(
		build/libcgltf.a
	)
	declare -a flags=(
		-P-I/usr/include/freetype2
		-L-lfreetype
		-Idlib
		--main
		--unittest
		-g
		-d-version=DLIB_TEST
		-verrors=50
		"--of=$out"
	)

	/bin/bash ./build.sh build

	# Test for success
	ldc2 "${flags[@]}" "${shared_src[@]}" "${native_src[@]}"

	rm "./${out}.o"
	"./${out}"
	rm $out

	native_src+=(
		vulkan/vulkan.d
		vulkan/vulkan_funcs.d
		opengl/opengl.d
		opengl/opengl_native.d
		opengl/glenum.d
		build/libvma.a
		dlib/dlibincludes.c
	)
	flags+=(
		-L-lvulkan
		-L-lstdc++
		-L-lGL
		-L-lX11
		-L-lSDL3
		-Jbuild
		-d-version=VULKAN_RENDERER_TEST
		-d-version=DLIB_ASSETS
		-d-version=BUILD_GL
		--Xcc=-DBUILD_VULKAN
		--Xcc=-DBUILD_ASSETS
		--Xcc=-DBUILD_GL
	)

	# Test for compilation
	$d_compiler "${flags[@]}" "${shared_src[@]}" "${native_src[@]}"

	rm "./${out}.o"
	"./${out}"
	rm $out
fi

