#!/bin/bash

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

LUA_VERSION="5.4.8"
LUA_SOURCE_DIR="lua-$LUA_VERSION"
LUA_ARCHIVE="lua-$LUA_VERSION.tar.gz"
LUASITE="https://www.lua.org/ftp/"

script=`readlink -f "$0" || echo "$0"`
top=`dirname "$script" || echo .`
packages="$top/packages"
stage="$top/stage"
stage_release="$stage/lib/release"
stage_debug="$stage/lib/debug"

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

let jobs=2
ncores=`cat /proc/cpuinfo | grep processor | wc -l`
if (( $ncores > 1 )) ; then
	jobs=$(($ncores / 2 + $ncores))
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"
mkdir -p "$stage_release"
mkdir -p "$packages"

if ! [ -d "$LUA_SOURCE_DIR" ] ; then
	if ! [ -f "$LUA_ARCHIVE" ] ; then
		wget "$LUASITE$LUA_ARCHIVE"
	fi
	tar xzf "$LUA_ARCHIVE"
fi

pushd "$LUA_SOURCE_DIR"

if [ -f "../hb-lua-$LUA_VERSION.patch" ] && ! [ -f hbpatched.txt ] ; then
	patch -p1 -s <"../hb-lua-$LUA_VERSION.patch"
	echo "Henri's patch applied" >hbpatched.txt
fi

if [ -f "../lua-$LUA_VERSION-bugfix.patch" ] && ! [ -f bugs-patched.txt ] ; then
	patch -p1 -s <"../lua-$LUA_VERSION-bugfix.patch"
	echo "Bug fixes applied" >bugs-patched.txt
fi

# Extract the copyright from the readme.html file
mkdir -p "$stage/LICENSES"
perl -ne 'print if m#<BLOCKQUOTE.*>#i .. m#</BLOCKQUOTE>#i' doc/readme.html | grep -v '<' >"$stage/LICENSES/lua.txt"

if [ "$1" == "--prepare" ] || [ "$1" == "-p" ] ; then
	# Copy the headers to the stage directory: only the built library will need
	# to be copied manually.
	pushd src
	cp -a lauxlib.h luaconf.h lua.h lua.hpp lualib.h "$stage/include/"
	popd
	popd
	echo
	echo "Sources prepared."
	exit 0
fi

make -j$jobs linux CFLAGS="$OPTFLAGS $DEBUGFLAGS $BUILDFLAGS -DLUA_USE_LINUX"

# Install in our package directory tree
pushd src
mv -f liblua.a "$stage_release/"
cp -a lauxlib.h luaconf.h lua.h lua.hpp lualib.h "$stage/include/"
popd

make clean

popd

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