#!/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/"

top=`pwd`
packages="$top/packages"
stage="$top/stage"
stage_release="$stage/lib/release"
stage_debug="$stage/lib/debug"

ARCHOPT="-m64 -fPIC"
OS="darwin64"

# Adjust for number of CPU cores +50%
let jobs=18

BUILDFLAGS="$ARCHOPT -fno-strict-aliasing -fno-stack-protector -mmacosx-version-min=10.8"
DEBUGFLAGS="-g"
OPTFLAGS="-O2 -msse2 -mfpmath=sse -fno-delete-null-pointer-checks"

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
		curl -L -o "$LUA_ARCHIVE" "$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

make -j$jobs macosx CFLAGS="$OPTFLAGS $DEBUGFLAGS $BUILDFLAGS -DLUA_USE_MACOSX"

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

# 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"

make clean

popd

pushd "$stage"
DATE=`date +%Y%m%d`
tar cyf "../liblua-$LUA_VERSION-$OS-$DATE.tar.bz2" *
popd
sleep 1
md5 -r "liblua-$LUA_VERSION-$OS-$DATE.tar.bz2"
