#!/bin/bash

# turn on verbose debugging output
set -x
# make errors fatal
set -e

SDL_VERSION="2.32.10"
SDL_SOURCE_DIR="SDL2-$SDL_VERSION"
SDL_ARCHIVE="SDL2-$SDL_VERSION.tar.gz"
SDLSITE="https://www.libsdl.org/release/"

script=`readlink -f "$0" || echo "$0"`
top=`dirname "$script" || echo .`
stage="$top/stage"
stage_include="$stage/include"
stage_release="$stage/lib/release"

arch=`uname -m`
if [ "$arch" == "x86_64" ] ; then
	OS="linux64"
	BUILD_ARCH_FLAGS="-m64"
	BUILD_OPT_FLAGS="-msse2 -mfpmath=sse"
elif [ "$arch" == "aarch64" ] ; then
	OS="linux-arm64"
	BUILD_ARCH_FLAGS=""
	BUILD_OPT_FLAGS="-march=armv8-a+fp+simd"
else
	echo "Sorry, 64 bits builds only, from now on !"
	exit 1
fi

BUILDFLAGS="$BUILD_ARCH_FLAGS -fPIC -fno-strict-aliasing -fno-stack-protector"
DEBUGFLAGS="-g -gdwarf-2 -gstrict-dwarf -fno-var-tracking-assignments"
OPTFLAGS="-O3 $BUILD_OPT_FLAGS -fno-delete-null-pointer-checks -fno-align-labels -fno-align-loops -fno-ipa-cp-clone -fsched-pressure -frename-registers -fweb"

cd $top

rm -rf "$stage/"
mkdir -p "$stage_include" "$stage_release" "$stage/LICENSES"

if ! [ -d "$SDL_SOURCE_DIR" ] ; then
	if ! [ -f "$SDL_ARCHIVE" ] ; then
		wget "$SDLSITE$SDL_ARCHIVE"
	fi
	tar xzf "$SDL_ARCHIVE"
fi

let jobs=2
ncores=`cat /proc/cpuinfo | grep processor | wc -l`
if (( $ncores > 1 )) ; then
	jobs=$(($ncores / 2 + $ncores))
fi

echo "================================================================"
echo "COMPILING: SDL (release)"
echo "================================================================"

pushd "$SDL_SOURCE_DIR"

# Do the release build of SDL
PATH="$stage"/bin/:"$PATH" \
CFLAGS="$BUILDFLAGS $DEBUGFLAGS $OPTFLAGS" \
CXXFLAGS="$BUILDFLAGS $DEBUGFLAGS $OPTFLAGS -std=c++11" \
./configure --prefix="$stage" --libdir="$stage_release" --includedir="$stage_include" --with-pic \
			--enable-ssemath --enable-sse2 --disable-3dnow --disable-mmx \
			--disable-audio --enable-joystick --disable-haptic --disable-sensor --disable-power \
			--disable-filesystem --disable-file --disable-cpuinfo --disable-sdl2-config \
			--with-x --disable-video-rpi --disable-video-cocoa --disable-video-vivante \
			--disable-video-opengles --disable-video-opengles1 --disable-video-opengles2 \
			--disable-video-vulkan --disable-video-wayland --disable-video-kmsdrm \
			--target=$TARGET
make -j$jobs V=1
make install

# Cleanup the build tree
make distclean

popd

cp -a "$top/$SDL_SOURCE_DIR/LICENSE.txt" "$stage/LICENSES/SDL.txt"
rm -rf "$stage/bin/" "$stage/share/"
rm -rf "$stage_release/"*.la "$stage_release/"*.a "$stage_release/pkgconfig/"

pushd "$stage"
DATE=`date +%Y%m%d`
tar cjf "../libSDL-$SDL_VERSION-$OS-$DATE.tar.bz2" .
popd
md5sum "libSDL-$SDL_VERSION-$OS-$DATE.tar.bz2"
