#!/bin/bash

set -e

EXACT=1
DIR=android

usage()
{
	echo 'Usage: $0 [ -t -d directory ]'
	echo -e 
	echo " -t                Reproduce the from the tip of the branch rather than doing"
	echo "                   an exact replica build"
	echo " -d <directory>    The directory to download code and build from"
	echo "                   Default: ${DIR}"
	exit 1
}

while getopts   "d:ht" optn; do
	case    $optn   in
		
		d   ) DIR=$OPTARG;;
		t   ) EXACT=0;;
		h   ) usage; exit 1;;
        esac
done

PKGS='zip curl flex bison build-essential git-core gnupg gperf zlib1g-dev libx11-dev x11proto-core-dev gcc-multilib g++-multilib libc6-dev-i386 ia32-libs lib32z-dev uboot-mkimage uuid-dev openjdk-6-jdk ant lib32ncurses5-dev'
MISSING=`dpkg-query -W -f='${Status}\n' ${PKGS} 2>&1 | grep 'No packages found matching' | cut -d' ' -f5`
if [ -n "$MISSING" ] ; then
	echo "Missing required packages:"
	for m in $MISSING ; do
		echo -n "${m%?} "
	done
	echo
	exit 1
fi

if [ -d ${DIR} ] ; then
	echo "Directory ${DIR} exists. Are you sure you want to use this? (y/n) "
	read CONTINUE
	[ ${CONTINUE} == y ] || exit 1
else
	mkdir ${DIR}
fi
cd ${DIR}

export MANIFEST_REPO=git://android.git.linaro.org/platform/manifest.git
export MANIFEST_BRANCH=linaro-android-12.07-release
export MANIFEST_FILENAME=tracking-vexpress.xml
export TARGET_PRODUCT=vexpress
export TARGET_SIMULATOR=false
export CPUS=`grep -c processor /proc/cpuinfo`
export TOOLCHAIN_URL=http://snapshots.linaro.org/android/~linaro-android/toolchain-4.7-2012.07/1/android-toolchain-eabi-linaro-4.7-2012.07-1-2012-07-16_08-48-35-linux-x86.tar.bz2
export TARGET_TOOLS_PREFIX=android-toolchain-eabi/bin/arm-linux-androideabi-

# download the repo tool for android
curl "http://android.git.linaro.org/gitweb?p=tools/repo.git;a=blob_plain;f=repo;hb=refs/heads/stable" > repo
chmod +x repo

# download the android code
./repo init -u ${MANIFEST_REPO} -b ${MANIFEST_BRANCH} -m ${MANIFEST_FILENAME} --repo-url=git://android.git.linaro.org/tools/repo.git
if [ ${EXACT} -eq 1 ] ; then
	rm .repo/manifest.xml
	curl -k http://snapshots.linaro.org/android/~linaro-android/vexpress-ics-gcc47-armlt-tracking-open-12.07-release/1//pinned-manifest.xml > .repo/manifest.xml
fi
./repo sync

# download the toolchain to build with
curl -k ${TOOLCHAIN_URL} > toolchain.tar.bz2
tar -jxf toolchain.tar.bz2
rm toolchain.tar.bz2

# build the code
. build/envsetup.sh
make -j${CPUS} boottarball systemtarball userdatatarball
