#!/bin/bash

set -e

#workdir=/home/jonas/src
#buildhost=auryn
#targetmachine=tibook
#newconfigdir=/debian/local/$buildhost/kernels/configs
#newkerneldir=/debian/local/$buildhost/kernels/images
#kernelpatches=NO
#ccompile=ccompile
#patchvars=
#kernel_headers=
#subarch=
. ./linux.conf

for var in workdir targetmachine newconfigdir newkerneldir; do
	if [ -z "`eval echo '$'$var`" ]; then
		echo "Variable '$var' missing. Exiting...!"
		exit 1
	fi
done

# Assume PowerPC is Macintosh if subarch is unset
if test "$subarch" = ""; then
	if test `dpkg-architecture -qDEB_HOST_ARCH` = "powerpc"; then
		subarch="pmac"
	fi
fi

OLDPWD="`pwd`"

cd ${workdir}/linux
if [ -z "$recompile" ]; then
	cp $newconfigdir/config-$targetmachine-LATEST_ATTEMPT .config
	cp $newconfigdir/config-$targetmachine-LATEST_ATTEMPT .config.old
	make oldconfig
	make-kpkg --rootcmd fakeroot ${kernelpatches:+--added-patches "$kernelpatches"} clean
fi
if [ -z "$onlyheaders" ]; then
	PATCH_THE_KERNEL=AUTO MAKEFLAGS=$MAKEFLAGS CONCURRENCY_LEVEL="$CONCURRENCY_LEVEL" $patchvars $ccompile make-kpkg --initrd --rootcmd fakeroot --revision 0.0.jones1 ${subarch:+--subarch "$subarch"} ${kernelpatches:+--added-patches "$kernelpatches" --append-to-version "+${kernelpatches//,/+}${kernelpatches_unofficial:++${kernelpatches_unofficial//,/+}}"} kernel_image $kernel_headers #"
else
	PATCH_THE_KERNEL=AUTO MAKEFLAGS=$MAKEFLAGS CONCURRENCY_LEVEL="$CONCURRENCY_LEVEL" $patchvars $ccompile make-kpkg --initrd --rootcmd fakeroot --revision 0.0.jones1 ${subarch:+--subarch "$subarch"} ${kernelpatches:+--added-patches "$kernelpatches" --append-to-version "+${kernelpatches//,/+}${kernelpatches_unofficial:++${kernelpatches_unofficial//,/+}}"} $kernel_headers #"
fi

cd ${workdir}
find . -mindepth 1 -maxdepth 1 -type f -name '*.deb' -exec mv '{}' $newkerneldir/$targetmachine ';'

cd "$OLDPWD"
