#!/bin/bash

set -x

KV_BASEURI="http://kernel.org/pub/linux/kernel"
OKV=${OKV:-${1}}
OKV=${OKV/_beta/-test}
OKV=${OKV/_rc/-rc}
OKV=${OKV/-r*}
OKV=${OKV/_p*}

PATCHDIR="$PWD/$2"

KV_MAJOR="$( echo $OKV | awk -F "." '{ print $1 }')"
KV_MINOR="$( echo $OKV | awk -F "." '{ print $2 }')"
KV_PATCH="$( echo $OKV | awk -F "." '{ print $3 }')"

if [ "${KV_MAJOR}${KV_MINOR}${KV_PATCH}" -ge 269 ] ; then
	__temp="${OKV/${KV_MAJOR}.${KV_MINOR}.${KV_PATCH}/}"

	[[ -n "$__temp" ]] && KV_EXTRA="${__temp}"
fi

KV="${KV_MAJOR}.${KV_MINOR}.${KV_PATCH}${KV_EXTRA}"

BASENAME="linux-${KV}.tar.bz2"
KV_URI="${KV_BASEURI}/v${KV_MAJOR}.${KV_MINOR}/$BASENAME"

if [ $# != "3" ] ; then
	echo "Usage: $0 kernelversion patchdir arch"
	exit 1
fi

if [ -x /usr/bin/wget ] ; then
	wget -nc -P /tmp $KV_URI >/dev/null 2>&1
	if [ "$?" -ne "0" ] ; then
		echo "An error occured while downloading $BASENAME!"
		exit 1
	fi
else
	echo "You're lacking net-misc/wget!!"
fi

if [ -x /bin/tar ] ; then
	[ -f /tmp/$BASENAME ] && tar xjf /tmp/$BASENAME -C /tmp 2>/dev/null
	if [ "$?" -ne "0" ] ; then
		echo "An error occured while unpacking $BASENAME!"
		exit 1
	fi
else
	echo "You're lacking app-arch/tar!"
	exit 1
fi

if [ -x /usr/bin/patch ]; then
	cd /tmp/${BASENAME/.tar.bz2/}
	PATCHES="$( ls -v $PATCHDIR/*.patch )"

	for X in $PATCHES ; do
		/usr/bin/patch -p1 -i $X
	done
else
	echo "You're lacking sys-devel/patch!"
	exit 1
fi

MAKEOPTS=${MAKEOPTS:=-j3}

cd /tmp/${BASENAME/.tar.bz2/}
make ARCH=$3 allmodconfig >/dev/null 2>&1

if [ "$?" -ne "0" ] ; then
	echo "An error occured while running \`make allmodconfig\'"
	exit 1
fi

make ARCH=$3 $MAKEOPTS 2>/tmp/$DATE-$KV-error.log \
	1>/tmp/$DATE-$KV-compile.log
if [ "$?" -ne "0" ] ; then
	echo "An error occured while running \`make ARCH=$3 $MAKEOPTS\'"
	exit 1
fi

[[ $? -eq "0" ]] && echo "[build-bot] ARCH: $3 - compilation for target \`allmodconfig\' successfully finished on $(date date +'%F %X')"
[[ $? -ne "0" ]] && echo "[build-bot] ARCH: $3 - compilation for target \`allmodconfig\' failed! See /tmp/$DATE-$KV-compile.log for details!"

