#!/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 "--- AT91Boot"
dirname="at91bootstrap-3-3.0"
tarname="$dirname.tar.gz"
wrs_download $tarname

#Export git version to the children call so that it can be use by Makefile
export WRS_GIT_USER="$(cd ${WRS_BASE_DIR} && git config --get user.name)"
export WRS_GIT_REV="$(cd ${WRS_BASE_DIR} && git describe --always --dirty)"

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
rm -rf $dirname
tar xzf $WRS_DOWNLOAD_DIR/$tarname || wrs_die "untar $tarname"

wrs_echo "Patching AT91Boot"
cd $dirname
for n in $WRS_BASE_DIR/../patches/at91boot/v3.3/*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

wrs_echo "Building AT91Boot"
cp $WRS_BASE_DIR/../patches/at91boot/v3.3/at91boot-wrs-config .config
make || wrs_die "building at91boot"
cp ./binaries/at91sam9g45ek-dataflashcardboot-3.0.bin \
    $WRS_OUTPUT_DIR/images/at91bootstrap.bin \
    || wrs_die "copying at91boot image"

exit 0
