#!/bin/bash
# This is the main build script. It must build all the environment
# variables for sub-scripts.

# Base dir is forcibly the dirname of this script, as an absolute pathname
dir=$(dirname $0)
WRS_BASE_DIR=$(cd $dir && /bin/pwd)
export WRS_BASE_DIR

. ${WRS_BASE_DIR}/scripts/wrs_functions


# See documentation for the meaning of these variables
wrs_setenv_default WRS_OUTPUT_DIR      $(/bin/pwd)
wrs_setenv_default WRS_DOWNLOAD_DIR    ${WRS_OUTPUT_DIR}/downloads

# Allow only absolute path for WRS_OUTPUT_DIR and WRS_DOWNLOAD_DIR
if [ "${WRS_OUTPUT_DIR:0:1}" != "/" ]; then
	wrs_die "Invalid WRS_OUTPUT_DIR, only absolute paths are allowed"
fi
if [ "${WRS_DOWNLOAD_DIR:0:1}" != "/" ]; then
	wrs_die "Invalid WRS_DOWNLOAD_DIR, only absolute paths are allowed"

fi
# make the directory, in case it's a completely new build
mkdir -p $WRS_DOWNLOAD_DIR

#project is WRS_BASE_DIR path without build directory at the end
project=${WRS_BASE_DIR:0:(${#WRS_BASE_DIR}-6)}
# Refuse to build within the wr-switch-sw directory
if echo $WRS_OUTPUT_DIR | grep "^$project.*\$" > /dev/null; then
	wrs_die "Please run $(basename $0) from a different directory outside the wr-switch-sw project"
fi

# Check the tools, also in /usr/sbin
export PATH="$PATH:/usr/sbin"
WRS_TOOLS="git gcc g++ ar as m4 msgfmt md5sum make"
WRS_TOOLS="$WRS_TOOLS awk unzip patch bison flex ncursesw5-config"
WRS_TOOLS="$WRS_TOOLS fakeroot makeinfo"

wrs_check_tools $WRS_TOOLS

# Create the directory for the "done" markers, as wrs_build_step needs it
export WRS_DONE_DIR=${WRS_OUTPUT_DIR}/build/_done
if ! [ -d "${WRS_DONE_DIR}" ]; then
    mkdir -p ${WRS_DONE_DIR} || wrs_die "mkdir failed"
fi

export WRS_SCRIPTS_DIR=${WRS_BASE_DIR}/scripts

## Function that show a little help
showhelp() {
	echo ""
	echo "Usage: $0 [options]"
	echo ""
	echo "Building script which fetch and compile the software for the white rabbit switch"
	echo ""
	echo "Options:"
	echo "	--help 		Show this little message"
	echo "	--pack		Create a tar.gz package with the files"
	echo "	--clean		Remove all the previous configuration"
	echo "	--list		List the different building steps"
	echo "	--step=<XX>	Perform specific step(s) (e.g. --step=01 or --step=\"5 7 9\")"
	echo ""
	exit 0;
}

clean()
{
	echo "Cleaning all outputs except downloads"
	make -C ${WRS_BASE_DIR}/../userspace clean
	rm -Rf ${WRS_OUTPUT_DIR}/build/
	rm -Rf ${WRS_OUTPUT_DIR}/images/
	exit 0
}

## Remove _done tag to a specific step or a list of steps like  --step="5 7 9" 
redo_step()
{
	for num in $1; do 
		rm -fv ${WRS_OUTPUT_DIR}/build/_done/$(printf "%02d" ${num})-*
	done
}



## Menu to select the function in case we have an argument
if [ -n "$1" ]; then
	case "$1" in
		--help) showhelp;;
		--clean) clean;;
		--list) cd $WRS_DONE_DIR; ls 0*; exit 0;;
		--pack) 
			echo "Normal build makes the pack too; nothing to do"
			exit 0;;
		--step=*) seq=$(echo "$1" | sed -e 's/--step=//');
			redo_step "$seq";;
		*) showhelp;;
	esac
fi

wrs_show_vars WRS_BASE_DIR WRS_OUTPUT_DIR WRS_DOWNLOAD_DIR \
    WRS_SCRIPTS_DIR WRS_DONE_DIR CROSS_COMPILE

# The function builds one step if needed: if the marker file exists, then the
# step has already been acoomplished and nothing is run this time
wrs_build_step () {
    markerfile="$WRS_DONE_DIR/$1"
    script="$WRS_SCRIPTS_DIR/$2"

    if [ -f $markerfile ]; then
	wrs_echo "$1 done; skipping script $2"
	return
    fi

    # Run another shell, so we can continue with the next step if it exits
    # I sometimes set WRS_SH_OPTIONS to "-x" to help me in debugging
    bash $WRS_SH_OPTIONS $script
    if [ $? -ne 0 ];
	then failed_step=true;
	else touch $markerfile
    fi
}





failed_step=false; # this is set to "true" but the wrs_build_step function

# Now build the stuff one step at a time, only if not already done.
# Steps 0 and 9 are redone in any case:
#   step 0 is downloading, and re-cecking md5sum has no side effects
#   step 9 is wrapping the filesystem: we need to re-wrap is something changed
redo_step "0 9"

#                 done-marker            script name
wrs_build_step    00-download            wrs_download
wrs_build_step    01-buildroot           wrs_build_buildroot
wrs_default_compiler
wrs_build_step    02-at91boot            wrs_build_at91boot
wrs_build_step    03-barebox             wrs_build_barebox
wrs_build_step    04-kernel              wrs_build_kernel
wrs_build_step    05-modules             wrs_build_modules
wrs_build_step    06-ptp                 wrs_build_ptp
wrs_build_step    07-wrs-userspace       wrs_build_userspace
wrs_build_step    08-wrs-gateware        wrs_build_gateware
wrs_build_step    09-wrap-rootfs         wrs_build_wraprootfs

if $failed_step; then
    wrs_die "One or more build steps failed"
fi
wrs_echo "Complete build succeeded, apparently"
