#!/bin/sh
set -e
SYSTEM="`readlink -f $1`"
ADENEO="`readlink -f $2`"
if ! [ -e "$SYSTEM" -a -e "$ADENEO" ]; then
	echo "Usage: $0 /path/to/system.tar.bz2 /path/to/Adeneo.tar.bz2"
	echo "Where system.tar.bz2 is the Linaro Android system.tar.bz2"
	echo "and Adeneo.tar.bz2 is the file you can download from"
	echo "http://adeneo-embedded.com/en/Products/Board-Support-Packages/Freescale-i.MX53-QSB/i.MX53-Android_SRC/%28version%29/768"
	echo "After registering with them."
	exit 1
fi
TMP="`mktemp -d /tmp/mx53-XXXXXX 2>/dev/null`"
if [ -z "$TMP" ]; then
	echo "You should install mktemp, working around its absence"
	TMP="/tmp/mx53.$$"
fi
mkdir -p "$TMP"
cd "$TMP"
tar xf "$SYSTEM"
if ! [ -d system/lib/egl ]; then
	cd /
	rm -rf "$TMP"
	echo "The system.tar.bz2 file you specified doesn't match"
	echo "what we're expecting. Make sure you're using a Linaro"
	echo "system.tar.bz2"
	exit 1
fi
tar xf "$ADENEO"
if ! [ -d i.MX53-QSB-Android-Gingerbread-Release4.1 ]; then
	cd /
	rm -rf "$TMP"
	echo "The file you specified doesn't match the file we're expecting."
	echo "If you're trying to use a newer version, edit the script."
	exit 1
fi
cd i.MX53-QSB-Android-Gingerbread-Release4.1/download
tar xf imx-android-r10.3.tar.gz
cd imx-android-r10.3/code/r10.3/device/fsl.git
git apply 0001-fsl.git-generate-fsl-patch.patch
cp -f proprietary/gpu/lib/* "$TMP"/system/lib
cp -f proprietary/gpu/egl/*.so "$TMP"/system/lib/egl/
mv "$TMP"/system/lib/egl/egl.cfg "$TMP"/system/lib/egl/egl.cfg.old
echo '0 1 imx51' >"$TMP"/system/lib/egl/egl.cfg
cat "$TMP"/system/lib/egl/egl.cfg.old >>"$TMP"/system/lib/egl/egl.cfg
rm -f "$TMP"/system/lib/egl/egl.cfg.old
cd "$TMP"
tar cjf "$TMP"/system.tar.bz2 system
cd ..
rm -rf system i.MX53-QSB-Android-Gingerbread-Release4.1
echo "Done. Use $TMP/system.tar.bz2 instead of the normal system.tar.bz2"
