#!/bin/bash

start_time=$(date +%s%N) # Performance timer

ProgramName="server_monitor"

# User defines
UserDefines="-DDEBUG"

# Compiler
CXX="g++"

CompilerFlags="-std=c++11"
CompilerFlags+=" -g"
#CompilerFlags+=" -fsanitize=address"
CompilerFlags+=" -fno-rtti -fno-exceptions"
CompilerFlags+=" -Wall -Wno-unused-variable -Wno-unused-but-set-variable -Wno-sign-compare -Wno-unused-value -Wno-unused-function -Werror=return-type -Wno-narrowing"

# Definitions and configuration
CompilerFlags+=" -DPLATFORM_LINUX=1"
#CompilerFlags+=" -DGUI_PERFORMANCE_REPORT"
CompilerFlags+=" -DSWAP_INTERVAL=1"

# Source files
SourceFiles="code/*.cpp"
SourceFiles+=" code/**/*.cpp"

# X11
CompilerFlags+=" -lX11 -lXi"

# OpenGL
CompilerFlags+=" -lGL -ldl"
CompilerFlags+=" -DGL_GLEXT_PROTOTYPES"
CompilerFlags+=" -DGLX_GLXEXT_PROTOTYPES"

# Pulseaudio
CompilerFlags+=" -lpulse"

# NetworkManager
CompilerFlags+=" "$(pkg-config --libs --cflags libnm)

# Libvirtd
CompilerFlags+=" -lvirt"

# External libs
CompilerFlags+=" -Iexternal"
ExternalFiles="external/*.cpp"
ExternalObjects=""
for f in $ExternalFiles;
do
	ObjName="cache_build/${f#"external/"}"
	ObjName=${ObjName%.cpp}.o
	ExternalObjects+=" ${ObjName}"
done
SourceFiles+="${ExternalObjects}"


# Cache external libs building. They are big and take a lot of time to compile
build_external=false
for obj in $ExternalObjects;
do
	if [ ! -e $obj ]
	then
		build_external=true
	fi
done

if [ $build_external == true ]
then
	echo "Building external libraries cache..."
	mkdir -p cache_build
	for f in $ExternalFiles;
	do
		ObjName="cache_build/${f#"external/"}"
		ObjName=${ObjName%.cpp}.o
		echo $ObjName
		$CXX $CompilerFlags $UserDefines -O2 $f -c -o $ObjName
	done
fi

echo "Compiling..."
$CXX $CompilerFlags $UserDefines $SourceFiles -o $ProgramName

compiled=$?
if [ $compiled != 0 ]
then
	exit $compiled
fi
echo "Done!"


end_time=$(date +%s%N) # Performance timer
duration_nanoseconds=$((end_time - start_time)) # Performance timer
duration_string="$((duration_nanoseconds/1000000/1000)).$((duration_nanoseconds/1000000%1000))"
echo #newline
echo "Duration: "$duration_string"s"
