#!/bin/bash
set -eu


for arg in "$@"; do declare $arg="1"; done
if [ ! -v clang ]; 												then gcc=1; fi
if [ ! -v release ]; 											then debug=1; fi
if [ -v debug ]; 													then echo "[debug mode]"; fi
if [ -v release ];												then echo "[release mode]"; fi
if [ -v gcc ]; 														then compiler="g++"; echo "[gcc compiler]"; fi
if [ -v clang ]; 													then compiler="clang++"; echo "[clang compiler]"; fi

if [ -v shaders ]; then
	echo "Bulding shaders..."
	/bin/bash ./build-shaders.sh
fi

# Axle
src="../src/entry_linux.cpp"
includes="-I../src/ -I../external/ -I../external/glad/include"
out="-o"
name="Axle"
linker_cmd=" "
link="-lpthread -lm -lrt -ldl -lxcb -lX11 -lGL -lXrandr"

# Codegen
codegen_src="../src/codegen.cpp"
codegen_name="Codegen"
codegen_flag="-DBUILD_CODEGEN"

# Packer
packer_src="../src/packer.cpp"
packer_name="Packer"
packer_flag="-DBUILD_PACKER"

if [ -x "$(command -v mold)" ]; then
	linker_cmd="-fuse-ld=mold"
fi

# clang
clang_common="${includes} ${linker_cmd} -DCOMPILER_CLANG -std=c++11 -Xclang -flto-visibility-public-std -Wno-write-strings -fdiagnostics-absolute-paths -Wall -Wno-missing-braces -Wno-unused-function -Wno-writable-strings -Wno-unused-value -Wno-unused-variable -Wno-deprecated-register -Wno-deprecated-declarations -Wno-unused-but-set-variable -Wno-single-bit-bitfield-constant-conversion -Wno-initializer-overrides -Wno-for-loop-analysis -ferror-limit=60"
clang_debug="$compiler -g -O0 -DBUILD_DEBUG=1 ${clang_common}"
clang_release="$compiler -O2 ${clang_common}"
clang_test="$compiler -O2 -DBUILD_TEST=1 ${clang_common}"

# gcc
gcc_common="${includes} ${linker_cmd} -DCOMPILER_GCC -std=c++11 -fmax-errors=5 -Wall -Wno-write-strings -Wno-missing-braces -Wno-unused-function -Wno-attributes -Wno-unused-value -Wno-unused-variable -Wno-deprecated-declarations -Wno-unused-but-set-variable -D_USE_MATH_DEFINES -Dstrdup=_strdup -Dgnu_printf=printf -fzero-init-padding-bits=unions"
gcc_debug="$compiler -g -O0 -DBUILD_DEBUG=1 ${gcc_common}"
gcc_release="$compiler -O2 ${gcc_common}"
gcc_test="$compiler -O0 -DBUILD_TEST=1 ${gcc_common}"

if [ -v gcc ]; 			then compile_debug="$gcc_debug"; fi
if [ -v gcc ]; 			then compile_release="$gcc_release"; fi

if [ -v clang ]; 		then compile_debug="$clang_debug"; fi
if [ -v clang ]; 		then compile_release="$clang_release"; fi

if [ -v debug ]; 		then compile="$compile_debug"; fi
if [ -v release ];	then compile="$compile_release"; fi

mkdir -p build

cd assets

mkdir -p shaders

cd ../build

if [ -v codegen ]; then
	echo "Building codegen..."
	$compile $codegen_src $codegen_flag $link $out $codegen_name
	./$codegen_name
fi

if [ -v packer ]; then
	echo "Building packer..."
	$compile $packer_src $packer_flag $link $out $packer_name
fi 

if [ -v pack ]; then
	echo "Packing assets..."
	./$packer_name
	./$codegen_name
fi

$compile $src $link $out $name

