#!/bin/bash
. ./BUILDDEFS

# Required for static linking, because CMake doesn't get them from SDL2
if [ "${KOBO_STATIC_LINUX}" = true ] ; then
	LINUX_EXTRA_LIBS="-lpthread -ldl -lrt -lm -lpng -lz"
else
	LINUX_EXTRA_LIBS=""
fi

# Similar problem as above, but for Win32
WIN32_EXTRA_LIBS="-lws2_32 -liphlpapi -lz"

shopt -s extglob
shopt -s nullglob

if [ $# -eq 0 ]; then
	FILTER=@(release|demo)
elif [ "$1" == all ]; then
	FILTER="*"
else
	FILTER="$1"
fi

mkdir -p $BUILDDIR

create_build_dir() {
	local dname=$1
	local btype=$2
	local desc=$3
	echo
	echo "=== build/$dname ($btype, $desc) ==="
	if [ ! -e $BUILDDIR/$dname ]; then
		mkdir $BUILDDIR/$dname
	fi
	if [ ! -e $BUILDDIR/$dname/src ]; then
		mkdir $BUILDDIR/$dname/src
	fi
	cd $BUILDDIR/$dname
}

setup_header() {
	local dname=$1
	local desc=$2
	echo
	echo "=========================================================="
	echo "Setting up build dirs for ${dname} ($desc)"
	echo "=========================================================="
}

setup_footer() {
	echo
	echo "=========================================================="
	echo "Done!"
	echo "=========================================================="
	echo
}

setup_native() {
	local dname=$1
	local btype=$2
	local desc=$3
	local prefix=$4
	local opts="$5"
	setup_header $dname "$desc"
	create_build_dir $dname $btype "$desc"
	cmake $opts $SOURCEDIR -DCMAKE_INSTALL_PREFIX=$prefix -DCMAKE_BUILD_TYPE="$btype" -DWORKDIR="${WORKDIR}" -DKOBO_EXTRA_LIBRARIES="${LINUX_EXTRA_LIBS}"
	cd $SOURCEDIR
	setup_footer
}

setup_cross() {
	local dname=$1
	local btype=$2
	local desc=$3
	local target=$4
	local opts="$5 -DWIN32_ZIP_BUILD=ON"
	if [ -e $MXEPATH ]; then
		setup_header $dname "$desc"
		create_build_dir $dname $btype "$desc"
		cmake $opts $SOURCEDIR -DCMAKE_BUILD_TYPE="$btype" -DCMAKE_TOOLCHAIN_FILE=$MXEPATH/usr/$target/share/cmake/mxe-conf.cmake -DBUILD_SHARED_LIBS=ON -DWORKDIR="${WORKDIR}" -DKOBO_EXTRA_LIBRARIES="${WIN32_EXTRA_LIBS}"
		cd $SOURCEDIR
		setup_footer
	else
		echo "MXE not found! Skipping target ${dname} ($desc)."
	fi
}

if [[ "release" = ${FILTER} ]] ; then
	setup_native release Release "host native" /usr
fi

if [[ "demo" = ${FILTER} ]] ; then
	setup_native demo Release "host native DEMO" /usr "-DDEMO_BUILD=ON"
fi

if [[ "maintainer" = ${FILTER} ]] ; then
	setup_native maintainer Maintainer "host native" /usr
fi

if [[ "debug" = ${FILTER} ]] ; then
	setup_native debug Debug "host native" /usr
fi

if [[ "mingw-release" = ${FILTER} ]] ; then
	setup_cross mingw-release Release "MXE cross" i686-w64-mingw32.shared
fi

if [[ "mingw-demo" = ${FILTER} ]] ; then
	setup_cross mingw-demo Release "MXE cross DEMO" i686-w64-mingw32.shared "-DDEMO_BUILD=ON"
fi

if [[ "mingw-debug" = ${FILTER} ]] ; then
	setup_cross mingw-debug Debug "MXE cross" i686-w64-mingw32.shared
fi
