#!/bin/bash -x


export BUILD_HOME=$(pwd)
export INSTALLED=${BUILD_HOME}/installed
export DJGPP=/opt/cross/djgpp


function buildGrx() {

	pushd grx249
	cp -f ${BUILD_HOME}/makedefs.grx .

	make -f makefile.dj2 clean
	make -f makefile.dj2 libs \
		CROSS_PLATFORM="${DJGPP}/bin/i586-pc-msdosdjgpp-" \
		C_FLAGS="-I${INSTALLED}/dos/include" \
		L_FLAGS="-L${INSTALLED}/dos/lib"
	cp -p -f lib/dj2/*.a ${INSTALLED}/dos/lib
	cp -p -f include/*.h ${INSTALLED}/dos/include
	make -f makefile.dj2 clean
	rm lib/dj2/lib*
	rm bin/*.exe

	make -f makefile.x11 clean
	make -f makefile.x11 libs \
		C_FLAGS="-I${INSTALLED}/linux/include" \
		L_FLAGS="-L${INSTALLED}/linux/lib"
	cp -p -f lib/unix/*.a ${INSTALLED}/linux/lib
	cp -p -f include/*.h ${INSTALLED}/linux/include
	make -f makefile.x11 clean
	rm lib/unix/lib*
	rm bin/{bin2c,fnt2c,xmodetest}

	popd
}


function buildJpeg() {
	pushd jpeg-9e

	(
		source ${DJGPP}/setenv
		sed -i 's/RM= del/RM= rm/g' makefile.dj
		cp -f jconfig.dj jconfig.h
		make -i -f makefile.dj clean
		make -i -f makefile.dj libjpeg.a
		cp -p -f *.a ${INSTALLED}/dos/lib
		cp -p -f *.h ${INSTALLED}/dos/include
		make -i -f makefile.dj clean
	)

	./configure --prefix=${INSTALLED}/linux --disable-shared
	make clean
	make
	make install
	make clean

	popd
}


function buildPng() {
	pushd libpng-1.6.37

	(
		source ${DJGPP}/setenv
		cp scripts/makefile.dj2 .
		sed -i "s#\-I\.\./zlib#\-I${INSTALLED}/dos/include \-DPNG_NO_CONSOLE_IO#g" makefile.dj2
		sed -i "s#\-L\.\./zlib/#\-L${INSTALLED}/dos/lib#g" makefile.dj2
		make -f makefile.dj2 clean
		make -f makefile.dj2 libpng.a
		cp -p -f *.a ${INSTALLED}/dos/lib
		cp -p -f *.h ${INSTALLED}/dos/include
		make -f makefile.dj2 clean
	)

	make clean
	cp scripts/makefile.linux .
	make -f makefile.linux clean
	make -f makefile.linux libpng.a
	cp -p -f *.a ${INSTALLED}/linux/lib
	cp -p -f *.h ${INSTALLED}/linux/include
	make -f makefile.linux clean

	popd
}


function buildZlib() {
	pushd zlib-1.2.12

	(
		source ${DJGPP}/setenv
		make clean
		./configure --prefix=${INSTALLED}/dos
		make
		make install
		make clean
		rm *.exe
	)

	make clean
	./configure --prefix=${INSTALLED}/linux --static
	make
	make install
	make clean

	popd
}


mkdir -p ${INSTALLED}/dos/{include,lib,share}
mkdir -p ${INSTALLED}/linux/{include,lib,share}

pushd thirdparty

buildZlib
buildPng
buildJpeg
buildGrx

popd
