#!/bin/bash

# check variables, like all scripts herein do
WRS_SCRIPT_NAME=$(basename $0)
if [ -z "$WRS_BASE_DIR" ]; then
    echo "$0: Plesae set WRS_BASE_DIR" >& 2
    exit 1
fi
. ${WRS_BASE_DIR}/scripts/wrs_functions

wrs_check_vars WRS_OUTPUT_DIR WRS_DOWNLOAD_DIR CROSS_COMPILE

wrs_echo "--- Barebox"
tarname="barebox-2012.05.0.tar.bz2"
wrs_download $tarname

mkdir -p $WRS_OUTPUT_DIR/build || wrs_die "mkdir build"
mkdir -p $WRS_OUTPUT_DIR/images || wrs_die "mkdir images"

# go to the build dir and compile it
cd $WRS_OUTPUT_DIR/build
dirname="barebox-2012.05.0"
rm -rf $dirname
tar xjf ${WRS_DOWNLOAD_DIR}/$tarname || wrs_die "untar $tarname"
cd $dirname
patchdir="$WRS_BASE_DIR/../patches/barebox/"
wrs_echo "Patching Barebox"
for n in $patchdir/*patch; do
    # the shell passes the "*" over if no matches are there, so check
    if test -f "$n"; then
	patch -p1 < $n || wrs_die "Apply $n"
    fi
done
cp "$patchdir/wrs3_defconfig" arch/arm/configs
cp -r $patchdir/env/* arch/arm/boards/pm9g45/env

wrs_echo "Building Barebox"
export ARCH=arm
make wrs3_defconfig || wrs_die "configure barebox"
make -s $WRS_MAKE_J || wrs_die "compile barebox"
cp barebox barebox.bin $WRS_OUTPUT_DIR/images \
    || wrs_die "copying barebox image"

exit 0
