#!/bin/sh

set -e

# start looking at our invokation line

if [ "$1" = --clean ]
then
	clean_flag=1
	shift
else
	clean_flag=0
fi

if [ $# != 2 ]
then
	echo "usage: $0 [--clean] target uart" 1>&2
	exit 1
fi

TARGET="$1"
UART_SEL="$2"

if [ ! -f "targets/$TARGET.h" ]
then
	echo "Error: target $TARGET not known" 1>&2
	exit 1
fi

case "$UART_SEL" in
	irda)
		RVTMUX_ON_MODEM=0
		;;
	modem)
		RVTMUX_ON_MODEM=1
		;;
	*)
		echo "Error: UART selection $UART_SEL not understood" 1>&2
		exit 1
esac

BUILD_DIR="build-$TARGET-$UART_SEL"

echo "Building FFS editor for target $TARGET (UART $UART_SEL) in $BUILD_DIR"

if [ "$clean_flag" = 1 ]
then
	rm -rf $BUILD_DIR
fi
mkdir -p $BUILD_DIR

# shell functions to be used in the configuration recipe

build_lib() {
	if [ $# != 1 ]
	then
		echo "Error: build_lib takes 1 argument" 1>&2
		exit 1
	fi
	scripts/mk-component.sh "$1"
	SUBDIR="$SUBDIR $1"
	LIBS="$LIBS $1/$1.a"
}

# invoke the configuration recipe

export BUILD_DIR TARGET RVTMUX_ON_MODEM

rm -rf $BUILD_DIR/config
cp -r cfg-headers $BUILD_DIR/config
cp targets/$TARGET.h $BUILD_DIR/config/fc-target.h

SUBDIR=
LIBS=

# core drivers
build_lib drivers_flash

build_lib riviera_core_flash
build_lib riviera_cust_flash

# services
build_lib dar
build_lib etm

# app drivers
build_lib buzzer
build_lib ffs
build_lib ffs_drv
build_lib uart_drv

# system glue
build_lib main
build_lib main_ir

# Nucleus
build_lib nucleus_flash
build_lib nucleus_intram

# selective libc replacement
build_lib libsys_fl
build_lib libsys_ir

# generate the top level Makefile!

helpers/makeline def SUBDIR $SUBDIR >> $BUILD_DIR/Makefile
echo >> $BUILD_DIR/Makefile
helpers/makeline def LIBS $LIBS >> $BUILD_DIR/Makefile
echo >> $BUILD_DIR/Makefile

cat gcc/makefile-body >> $BUILD_DIR/Makefile

# All done!

echo "Run make in $BUILD_DIR to compile the application"
