#!/bin/sh

# files match if they are the same name or have the same contents
files_match() {
	[ "$1" == "$2" ] && return 0
	[ -z "$1" ] && return 1
	[ -z "$2" ] && return 1
	[ -e "$1" ] || return 1
	[ -e "$2" ] || return 1
	[ `sha256sum "$1" | cut -d' ' -f 1` == `sha256sum "$2" | cut -d' ' -f 1` ]
	return $?
}

# kconfigs match if non-comment data matches
kconfig_match() {
	[ "$1" == "$2" ] && return 0
	[ -z "$1" ] && return 1
	[ -z "$2" ] && return 1
	[ -e "$1" ] || return 1
	[ -e "$2" ] || return 1
	local h1=`cat "$1" | grep -v '^#\|^$' | sort | uniq | sha256sum | cut -d' ' -f 1`
	local h2=`cat "$2" | grep -v '^#\|^$' | sort | uniq | sha256sum | cut -d' ' -f 1`
	[ "$h1" == "$h2" ]
	return $?
}

# copy file $1 to $2 if they don't match based on $3 (or files_match by default)
cp_if_not_match() {
	local match=files_match
	if [ "$#" -eq 3 ]; then
		match=$1
		shift
	fi
	[ "$#" -ne 2 ] && return 127
	if ! $match "$1" "$2"; then
		cp -dv --preserve=mode,ownership "$1" "$2"
		[ $? -ne 0 ] && return 127
		return 1
	else
		echo "$1 ($2) is unchanged"
	fi
	return 0
}

# Change directory to project directory
cd $TOPDIR

if ! [ -e $TOPDIR/$DEF_FILE ]
then
	echo "$DEF_FILE is missing. Check if SUBPROJECT option is needed"
	exit 1
fi
. $TOPDIR/$DEF_FILE

# Check if Build directory is present
if ! [ -d $TOPDIR/$BUILD_DIR ]
then
	echo -n "Creating $TOPDIR/$BUILD_DIR ..."
	mkdir -p $TOPDIR/$BUILD_DIR
	if [ $? -eq 0 ]
	then
		echo "Done"
	else
		echo "Failed"
		exit 1
	fi
fi

BUILDNUMBER_FILE=$TOPDIR/$BUILD_DIR/buildnumber.h
# Create the build number file that contains the subversion revision
if ! [ -e $TOPDIR/TreeIsBinary ]
then
    sh $TOPDIR/scripts/BuildNum2H $BUILDNUMBER_FILE
    if [ $? -ne 0 ]
    then
        echo "failed to create the build number file...aborting"
        exit 1
    fi
else
    if ! [ -h $TOPDIR/$BUILD_DIR/buildnumber.h ]
    then
        echo "Binary tree detected. Linking build number header."
        ln -s ../core/buildnumber.h $TOPDIR/$BUILD_DIR/buildnumber.h
    fi
fi

# Create Project Definition files
sh $TOPDIR/scripts/ProjDef2H
if [ $? -ne 0 ]
then
    exit 1
fi

if ! [ -e $TOPDIR/$CONF_DIR/config.$SUBPROJECT ]
then
    echo "Platform configuration file $TOPDIR/$CONF_DIR/config.$SUBPROJECT does not exist...Aborting"
    exit 1
else
    cp_if_not_match $TOPDIR/$CONF_DIR/config.$SUBPROJECT $TOPDIR/$BUILD_DIR/platformcfg.h
    if [ $? -eq 127 ]
    then
        echo "Failed to copy $TOPDIR/$CONF_DIR/config.$SUBPROJECT to $TOPDIR/$BUILD_DIR/platformcfg.h...Aborting"
        exit 1
    fi



    cp_if_not_match $TOPDIR/$BUILD_DIR/platformcfg.h $TOPDIR/core/platformcfg.h
    if [ $? -eq 127 ]
    then
        echo "Failed to link $TOPDIR/core/platformcfg.h to $TOPDIR/$BUILD_DIR/platformcfg.h ...Aborting"
        exit 1
    fi
fi


# Extract target  and Apply Patches if not done already
if ! [ -d $TOPDIR/$BUILD_DIR/target ]
then
	sh $TOPDIR/scripts/ExtractTarget
	if [ $? -ne 0 ]
	then
		exit 1
	fi
fi

if ! [ -d $TOPDIR/$BUILD_DIR/target.new ]
then
	sh $TOPDIR/scripts/ExtractTarget
	if [ $? -ne 0 ]
	then
		exit 1
	fi
fi


#Build SFCB
sh $TOPDIR/scripts/BuildSFCB
if [ $? -ne 0 ]
then
	exit 1
fi


# Build Linux
echo "============================================================================================="
echo "Building Linux kernel"
echo "============================================================================================="

cd $TOPDIR/core/linux

cp_if_not_match kconfig_match "$TOPDIR/$CONF_DIR/config.linux" ".config"
COPIED_UPDATED_FILE=$?
if [ $COPIED_UPDATED_FILE -eq 127 ]
then
	echo "Unable to copy config.linux file. Cannot build linux"
	exit 1
fi

if [ $COPIED_UPDATED_FILE -eq 1 ]
then
	make oldconfig
	if [ $? -ne 0 ]
	then
		echo "Unable to create linux config file. make oldconfig failed"
		exit 1
	fi
	# cp_if_not_match kconfig_match ".config" "$TOPDIR/$CONF_DIR/config.linux"
fi

# Basic linux Build
make CONFIG_DEBUG_SECTION_MISMATCH=y uImage modules
if [ $? -ne 0 ]
then
	echo "Linux Build failed. Aborting"
	exit 1
fi

echo "Installing ibmc drivers..."
export INSTALL_MOD_PATH=$TOPDIR/$BUILD_DIR/target
make modules_install
if [ $? -ne 0 ]
then
	echo "ibmc drivers install failed. Aborting"
	exit 1
fi

# Install the signed_image.h file to build dir because userspace uses it
mkdir -p $TOPDIR/$BUILD_DIR/target/usr/include/linux/mtd
ln -s $TOPDIR/core/linux/include/linux/mtd/signed_image.h $TOPDIR/$BUILD_DIR/target/usr/include/linux/mtd

#BINARYDIR=$TOPDIR/development/binaries
#BIN_DRIVERS_DIR=$BINARYDIR/lib/modules/$LINUX_VER/misc
#mkdir -p $BIN_DRIVERS_DIR  &&  cp $IBMC_DRIVERS $BIN_DRIVERS_DIR
#if [ $? -ne 0 ]
#then
#	echo "ibmc drivers install to binaries dir failed. Aborting"
#	exit 1
#fi



# Build uboot
echo "============================================================================================="
echo "Building Das U-boot for board $BOARD"
echo "============================================================================================="

cd $TOPDIR/core/fsafe_boot/uboot

if [ -e "$TOPDIR/$CONF_DIR/u-boot.lds" ];
then
	cp_if_not_match "$TOPDIR/$CONF_DIR/u-boot.lds" "board/$BOARD/u-boot.lds"
	if [ $? -eq 127 ]
	then
		echo "Unable to copy u-boot.lds file. Cannot build uboot"
		exit 1
	fi
fi

SAVED_BUILD_DIR=$BUILD_DIR
export BUILD_DIR=

mkdir -p "include/configs"
cp_if_not_match "$TOPDIR/$CONF_DIR/config.uboot" "include/configs/$BOARD.h"
COPIED_UPDATED_FILE=$?
if [ $COPIED_UPDATED_FILE -eq 127 ]
then
	echo "Unable to copy config.uboot file. Cannot build uboot"
	exit 1
fi

# only do a $BOARD_config if it is not already configured
if [ ! -e include/config.mk ]
then
	make $BOARD"_config"
	if [ $? -ne 0 ]
	then
		echo "Unable to create uboot config file. make $BOARD""_config failed"
		exit 1
	fi
fi

make
RET=$?
if [ $RET -ne 0 ]
then
	echo "Uboot Build failed with $RET. Aborting"
	exit 1
fi

# Backup the u-boot.bin file and then create a compressed uboot image
cp u-boot.bin u-boot_backup.bin
gzip -f u-boot.bin
cp u-boot_backup.bin u-boot.bin

export BUILD_DIR=$SAVED_BUILD_DIR
SAVED_BUILD_DIR=

# Build busybox
echo "============================================================================================="
echo "Building busybox"
echo "============================================================================================="

cd $TOPDIR/core/busybox

cp_if_not_match kconfig_match $TOPDIR/$CONF_DIR/config.busybox .config
COPIED_UPDATED_FILE=$?
if [ $COPIED_UPDATED_FILE -eq 127 ]
then
	echo "Unable to copy config.busybox file. Cannot build busybox"
	exit 1
fi
if [ $COPIED_UPDATED_FILE -eq 1 ]
then
	echo "Generating config..."
	make oldconfig >&/dev/null
	if [ $? -ne 0 ]
	then
		echo "Unable to create busybox config file. make oldconfig Failed"
		exit 1
	fi


	if [ "$BUSYBOX_VER" == "1.1.3" ]
	then
		# Newer versions of busybox does not require this
		echo "Creating dependency file for Busybox"  $BUSYBOX_VER
		# Note: .depend will be automatically created by make all also
		#        But when parallel make (-j) is done, .depend and related
		#        file are created later than the object files. This will
		#        create wrong outputs and also when running install, because
		#	 of newer dependeny files, it is rebuild agin.
		make .depend
		if [ $? -ne 0 ]
		then
			echo "Unable to create dependency file for busybox. Aborting"
			exit 1
		fi
	fi
fi

make all
if [ $? -ne 0 ]
then
	echo "BusyBox Build failed. Aborting"
	exit 1
fi


# Build libs
echo "============================================================================================="
echo "Building libs"
echo "============================================================================================="

cd $TOPDIR/core/lib

./build_libs build
if [ $? -ne 0 ]
then
	echo "Failed to build libs. Aborting"
	exit 1
fi

echo "============================================================================================="
echo "Installing libs and headers"
echo "============================================================================================="
./build_libs install
if [ $? -ne 0 ]
then
	echo "Failed to install libs/headers. Aborting"
	exit 1
fi


# Build libs
echo "============================================================================================="
echo "Building core apps"
echo "============================================================================================="

cd $TOPDIR/core/apps

./build_apps build
if [ $? -ne 0 ]
then
	echo "Failed to build apps. Aborting"
	exit 1
fi

echo "============================================================================================="
echo "Installing core apps"
echo "============================================================================================="
./build_apps install
if [ $? -ne 0 ]
then
	echo "Failed to install apps. Aborting"
	exit 1
fi


exit 0
