#!/bin/bash

set -e

export BBPATH=.:/home2/rw/openembedded/oz354fam083/org.openembedded.oz354fam083/

# build directory
B_DIR="build-familiar-0.8.3-multimachine"

# target machines
MACHINES="h3600 h3900 h2200 h6300 ipaq-pxa270 simpad"

# images to build apart from bootstrap
EXTRA_IMAGES="gpe opie"

# some packages that don't play nice with PACKAGE_ARCH or otherwise need to be cleaned
ALL_CLEAN_PKGS="base-files/base-files libtool/libtool-cross modutils/modutils-cross module-init-tools/module-init-tools-cross"
BOOTSTRAP_CLEAN_PKGS="sysvinit/sysvinit"
GPE_CLEAN_PKGS="tslib/tslib"
OPIE_CLEAN_PKGS="tslib/tslib opie*/opie-button-settings"

echo "Multimachine build for $MACHINES."
for img in bootstrap $EXTRA_IMAGES; do
	if [ -f ${img}.stamp ]; then
		echo "$img images already done."
	else
		# ${B_DIR} must not exist beforehand
		if [ -d ${B_DIR} ]; then
			echo "${B_DIR} exists."
			exit 1
		fi

		# prepare build dir
		if [ -d ${B_DIR}.${img} ]; then
			mv ${B_DIR}.${img} ${B_DIR}
		else
			if [ ${img} == "bootstrap" ]; then
				mkdir -p ${B_DIR}/conf
				cp ../confs/local.conf ${B_DIR}/conf
			else
				cp -a ${B_DIR}.bootstrap ${B_DIR}
			fi
		fi

		# change into build dir and run the build
		cd ${B_DIR}
		for machine in $MACHINES; do
			if [ -f tmp/deploy/images/${img}-image-${machine}.stamp ]; then
				echo "${img}-image for $machine already done."
				continue
			fi

			echo "Building ${img}-image for $machine."

			# create auto.conf for ${machine}
			if ! grep -q "MACHINE.*${machine}" conf/auto.conf; then
				echo "MACHINE = \"$machine\"" > conf/auto.conf
				cat ../confs/${img} >> conf/auto.conf
			fi

			# clean non-multimachine-aware packages and run the build
			for pkg in $ALL_CLEAN_PKGS $BOOTSTRAP_CLEAN_PKGS; do
				for i in ../org*/packages/$pkg*bb; do
					bitbake -b $i -c clean
				done
			done

			# clean even more packages...
			if [ -f clean_pkgs.txt ]; then
				cat clean_pkgs.txt | xargs bitbake -k -c clean
			fi

			if [ -f refetch ]; then
				bitbake -f -c fetch ${img}-image
			fi
			bitbake ${img}-image

			touch tmp/deploy/images/${img}-image-${machine}.stamp
		done
		rm -f clean_pkgs.txt

		# fix permissions of quilt patches after first bootstrap build so that dir
		# can be copied over for subsequent image types
		for img2 in $IMAGES; do
			if [ ${img} == "bootstrap" -a ! -d ../${B_DIR}.${img2} ]; then
				for i in `find . -name '.pc'`; do
					chmod -f -R u+rw $i
				done
				break
			fi
		done
		cd ..
		mv ${B_DIR} ${B_DIR}.${img}
		touch ${img}.stamp
	fi
done

echo "done."
