#!/bin/bash
# Mesa-O-Matic
# Copyright 2011-2013, Alexander von Gluck IV
# Released under the terms of the MIT license

# This script creates an optional package containing the
# the headers and binary code needed by the opengl kit
# to link libGL.so and the OpenGL add-ons

# This script is run against a *COMPILED* Mesa source tree

echo " Welcome to Mesa-O-Matic!"
echo "-=-=-=-=-=-=-=-=-=-=-=-=-="
echo ""

if [[ $DEBUG -eq 1 ]]; then
	echo "Debugging: enabled"
else
	echo "Debugging: disabled"
fi

#######################################################################
# END CONFIG DATA, Dragons below!
#######################################################################

function piraterepack {
	# Ar. Ye be a hack.
	# Provided a list of .a's, repack them together
	PACKTMP=/tmp/repack
	rm -rf $PACKTMP
	mkdir $PACKTMP
	for i in $1
	do
		if [[ "$1" = /* ]]
		then
			# Absolute path
			cp $i $PACKTMP/ ;
		else
			find . -name "$i" -exec cp "{}" $PACKTMP/ \;
		fi
	done
	cd $PACKTMP
	find . -name "*.a" -exec ar x "{}" \;
	rm *.a
	ar rcs $2 *
	cd -
	cp $PACKTMP/$2 ./build/
	rm -rf $PACKTMP
}

if [[ $( uname ) != "Haiku" ]]; then
	echo "*************************************"
	echo " I need to be run on a Haiku system!!"
	echo "*************************************"
	exit 1
fi

if [[ -z $1 ]]; then
	echo ""
	echo "Usage: $0 <mesa version> <compiled mesa location>"
	echo ""
	exit 1
fi

MESA_VER="$1"
MESA_TOP="$2"
GCC_VER=`gcc -v 2>&1 | tail -1 | awk '{print $3}' | cut -d. -f1`
DATESTAMP=`date +"%Y-%m-%d"`

echo "Bundling gcc$GCC_VER build of Mesa $MESA_VER..."

cd $MESA_TOP

#######################################################################
# Create Mesa optional pacakge
ZIP_HEADERS=""
echo "Collecting Mesa headers..."
for i in $(find . -name "*.h")
do
	ZIP_HEADERS="$ZIP_HEADERS $i"
done

echo "Collecting required Mesa libraries..."

rm -rf lib.haiku

BASE_LIBS="libglapi.a libmesa.a"

if [[ $GCC_VER -ge 4 ]]; then
BASE_LIBS="$BASE_LIBS libgallium.a libglsl.a"

# Repack the Mesa objects into an easy to digest archives
# These bundles are linked into OpenGL add-ons

## llvmpipe bundle
LLVM_LIBS=`llvm-config --libfiles engine bitwriter mcjit`
piraterepack "$LLVM_LIBS" "swpipe_llvm.a"
piraterepack "swpipe_llvm.a libsoftpipe.a libllvmpipe.a" \
	"swpipe_bundle.a"
BASE_LIBS="$BASE_LIBS swpipe_bundle.a"

## r600 bundle
## etc bundle
fi

mkdir -p lib.haiku
for i in $BASE_LIBS 
do
	find ./build/ -name "$i" -exec cp -f {} lib.haiku/ \;
	if [[ $? -ne 0 ]]; then
		echo "Warning: couldn't locate $i"
	fi
done

if [[ $DEBUG -eq 0 ]]; then
echo "Stripping debug symbols from Mesa libraries..."
find lib.haiku/* -exec strip --strip-debug {} \; ;
MESADBG=""
else
MESADBG="dbg"
fi

echo "Creating Mesa OptionalPackage..."
PLATFORM=$( uname -m )
ZIP_FILENAME="/boot/home/mesa-${MESA_VER}-x86${MESADBG}-gcc${GCC_VER}-${DATESTAMP}.zip"
zip -r -9 $ZIP_FILENAME $ZIP_HEADERS ./lib.haiku/*

echo "Great Success! $ZIP_FILENAME created."
