#!/bin/bash
#
# Copyright (C) 2008-Present Sigma Desings
#
#
# Contact Info                       History
# <ken_zhai@sdesigns.com>            Initiated the recursive makefile structure
#
#
# Sigma Designs
# 1778 McCarthy BLVD
# Milpitas CA 95035, USA
#
#
set -e
TOPDIR=`pwd`
AWK=gawk

if [ ! -f .config ]; then
cp .defconfig .config
fi
source .config

function copy_tree()
{
        [ -d $2 ] || mkdir -p $2
        cd $1
        mylist=`find . -type f -name "*"`
        for x in $mylist
        do
                mypath=${x%/*}
                myfile=${x##*/}
                y=$mypath
                mycvs=${y##*/}
                if test "$mycvs" != "CVS" ; then
                        if test "$mypath" != "." ; then
                                [ -d $2/$mypath ] || mkdir -p $2/$mypath
                        fi
                        cp -a $x $2/$x
                fi
        done
}

function apply_it()
{
        checkit 1 $@
        for x in ${ay[@]}
        do
                $1 $x
        done
}

function do_magic()
{
checkit 1 $*
sed "s!\"!!g" $1 | $AWK 'BEGIN { FS="="; num=getfile(".makefile.in",fpart,num) }
	/^[^#]/ { line[NR]=$0 ; output(line[NR],$1,num,fpart) }
	function output(line,key,num,fpart) {
		apply="YES"
		for(i=1;i<num;i++)
		{
			if(key==fpart[i]) apply="NO"
		}
		if(apply!="NO")
			print line >> ".makefile.in"
	}
	function getfile(file,fpart,inc) {
		while (getline <file >0)
			fpart[++inc]=$1
		return ++inc
	}'
}

function do_magic1()
{
checkit 1 $*
$AWK '
	#read first file
	BEGIN { FS="="; num=sethashtable(".makefile.in",myhash,myidx,num) }
	#Create a hash table by using first entry as a hash index from a input file	
	function sethashtable(file,myhash,myidx,inc) {
	while (getline <file >0) {
		split ($0, entry, "=")
		myidx[++inc]=entry[1]
		myhash[myidx[inc]]=$0
		}
		return ++inc
	}
	#Process any input line containing pattern entry
	/^[^#]/ {
		if($1 in myhash) {
		myhash[$1]=$0
		}
	}
	END {
		for(i=1;i<num;i++) {
			print myhash[myidx[i]] >> ".outconfig"
		}
	}' $1
if [ -f ".outconfig" ]; 
then	
	mv .outconfig .makefile.in
fi
$AWK 'BEGIN { FS="="; num=getfile(".makefile.in",fpart,num) }
        /^[^#]/ { line[NR]=$0 ; output(line[NR],$1,num,fpart) }
        function output(line,key,num,fpart) {
                apply="YES"
                for(i=1;i<num;i++)
                {
                        if(key==fpart[i]) apply="NO"
                }
                if(apply!="NO")
                        print line >> ".makefile.in"
        }
        function getfile(file,fpart,inc) {
                while (getline <file >0)
                        fpart[++inc]=$1
                return ++inc
        }' $1
}

function do_magic2()
{
checkit 1 $*
sed "s!\"!!g" $1 | $AWK 'BEGIN { FS="\n"; num=getfile("rootfs-path.env",fpart,num) }
	/^[^#]/ { line[NR]=$0 ; output(line[NR],$1,num,fpart) }
	function output(line,key,num,fpart) {
		apply="YES"
		for(i=1;i<num;i++)
		{
			if(key==fpart[i]) apply="NO"
		}
		if(apply!="NO")
			print line >> "rootfs-path.env"
	}
	function getfile(file,fpart,inc) {
		while (getline <file >0)
			fpart[++inc]=$1
		return ++inc
	}'
}

function checkit()
{
if [ "$#" = "0" ]; then
        echo "Usage: checkit 2 \$abc \$xyz"
        return
fi
let max=$1+1

n=0
while true; do
        let n=n+1
        if [ "$n" = "$max" ]; then
                break
        fi
        case "$n" in
                1 )
                        if [ -z "$2" ]; then make_error; fi
                ;;
                2 )
                        if [ -z "$3" ]; then make_error; fi
                ;;
                3 )
                        if [ -z "$4" ]; then make_error; fi
                ;;
                4 )
                        if [ -z "$5" ]; then make_error; fi
                ;;
                5 )
                        if [ -z "$6" ]; then make_error; fi
                ;;
                6 )
                        if [ -z "$7" ]; then make_error; fi
                ;;
                7 )
                        if [ -z "$8" ]; then make_error; fi
                ;;
                8 )
                        if [ -z "$9" ]; then make_error; fi
                ;;
                * ) ;;
        esac
done
}

function create_to_config()
{
	echo "$@" > .tmpfile
}

function append_to_config()
{
	checkit 1 $@
	if [ ! -z $2 ]; then
		echo "$1=\"$2\"" >> .tmpfile
	else		
		echo "$1=\"${!1}\"" >> .tmpfile
	fi
}

function echo_to_config()
{
	echo "$@" >> .tmpfile
}

function export_to_config()
{
	checkit 1 $@
	if [ ! -z $2 ]; then
		eval "$1=\"$2\""
	else		
		eval "$1=\"${!1}\""
	fi
	append_to_config $1
	echo_to_config "export $1"
}

function func1()
{
ay=($ROOTFS_TMP_DIR $ROOTFS_LIB $ROOTFS_BIN $ROOTFS_SBIN $ROOTFS_USR $ROOTFS_INC)
ay=($DL_DIR ${ay[@]})
for x in ${ay[@]}
do
	[ -d $x ] || mkdir -p $x
done
}

function func2()
{
	checkit 3 $*
	ay=($TOOL_BUILD_DIR  $BUILD_DIR)
	for x in ${ay[@]}
	do
		[ -d $x ] || mkdir -p $x
	done
	if [ -f "$1" ] ; then
		pushd $3/..; zcat $1 | tar -C . -xf -; popd
	fi
	if [ -d "$2" ] ; then 
		copy_tree  $2 $3 
	fi;
}

function setup_env()
{
	gen_rootfs-path_env rootfs-path.env
}

function gen_make_rules()
{
echo "-include \$(TOPDIR)/.config" > .makefile.rules
echo "-include \$(TOPDIR)/Makefile.in" >> .makefile.rules
echo "-include Configure" >> .makefile.rules
echo "-include \$(BASE_DIR)/makefile.policy" >> .makefile.rules
echo "ifeq '\$(TARGET_DIR)' ''" >> .makefile.rules
echo "\$(error Something is wrong on your build!)" >> .makefile.rules
echo "endif" >> .makefile.rules
echo "ifeq '\$(ROOTFS_TMP_DIR)' ''" >> .makefile.rules
echo "\$(error Something is wrong on your build!)" >> .makefile.rules
echo "endif" >> .makefile.rules
echo "ifeq '\$(STAGING_DIR)' ''" >> .makefile.rules
echo "\$(error Something is wrong on your build!)" >> .makefile.rules
echo "endif" >> .makefile.rules
}

function gen_make_path()
{
if [ $# = 1 ] ; then 
setup_env $1
exit
else
setup_env $1
source .config
BASE_DIR=$TOPDIR
ROOTFS_TMP_DIR=$BASE_DIR/tmp
ROOTFS_LIB=$ROOTFS_TMP_DIR/lib
ROOTFS_BIN=$ROOTFS_TMP_DIR/bin
ROOTFS_SBIN=$ROOTFS_TMP_DIR/sbin
ROOTFS_USR=$ROOTFS_TMP_DIR/usr
ROOTFS_INC=$ROOTFS_TMP_DIR/include
DL_DIR=$BASE_DIR/dl
TARGET_SKEL_DIR=$BASE_DIR/target/generic/target_skeleton
TARGET_SKELETON=$BASE_DIR/target/generic/skel.tar.gz
func1
if [ "$2" != "" ]; then 
	BUILD_DIR=$BASE_DIR/build_$2$3
	TARGET_DIR=$BASE_DIR/build_$2$3/root
	TOOL_BUILD_DIR=$BASE_DIR/toolchain_build_$2$3
	checkit 2 $*
	[ -d $TARGET_DIR ]|| mkdir -p $TARGET_DIR
	func2 $TARGET_SKELETON  $TARGET_SKEL_DIR $TARGET_DIR
else
	echo "missing argument!"
fi
fi
}

function add_to_path_before() {
        checkit 1 $@
        local v1=$PATH

        if [ -z "$v1" ] ; then
                v1=$1
        else
                if test ! "`echo "$v1" | egrep -wos "$1"`" ; then
                        v1="$1:$v1"
                fi
        fi
        PATH=$v1
}

function add_to_path_after() {
        checkit 1 $@
	local p="$1=${!1}:\$$1"
        local v1=${!1}

        if [ -z "$v1" ] ; then
                p="$1=\$$1"
        else
                if test ! "`echo "$v1" | egrep -wos "\$$1"`" ; then
			p="$1=$v1:\$$1"
                fi
        fi
	[ ! -f .tmpfile ] || rm -f .tmpfile
	create_to_config "$p"
}

function add_to_compilkind()
{
	local v1=$COMPILKIND
	local pt=`echo $1`
	if [ -z "$v1" ] ; then
		v1=$1
	else 
		if [ "`echo $v1 | egrep -wcs $pt`" = "0"  ] ; then
			v1="$v1 $1"
		fi
	fi
	COMPILKIND=$v1
}

function add_to_path()
{
	echo "add_to_path_before /bin" > .tmpfile
	echo "add_to_path_before /sbin" >> .tmpfile
	echo "add_to_path_before /usr/bin" >> .tmpfile
	echo "add_to_path_before /usr/sbin" >> .tmpfile
	echo "add_to_path_before /usr/local/bin" >> .tmpfile
	echo "add_to_path_before /usr/local/sbin" >> .tmpfile
	echo "add_to_path_before \$SMP86XX_TOOLCHAIN_PATH/bin" >> .tmpfile
	echo "add_to_path_before \$SMP86XX_ROOTFS_PATH/cross_rootfs/bin" >> .tmpfile
	echo "add_to_path_before \$SMP86XX_ROOTFS_PATH/host/bin" >> .tmpfile
}

function gen_rootfs-path_env()
{
if [ -z "$COMPILKIND" ]; then
#The default is release codesourcery hardfloat glibc
	COMPILKIND="release codesourcery hardfloat glibc"
else
add_to_compilkind codesourcery 
	if [ "`echo $COMPILKIND | egrep -wcs debug`" = "0"  ] ; then
		add_to_compilkind release
	fi
	if [ "`echo $COMPILKIND | egrep -wcs non-codesourcery`" = "0"  ] ; then
		add_to_compilkind codesourcery
	fi
	if [ "`echo $COMPILKIND | egrep -wcs softfloat`" = "0"  ] ; then
		add_to_compilkind hardfloat
	fi
	if [ "`echo $COMPILKIND | egrep -wcs uclibc`" = "0"  ] ; then
		add_to_compilkind glibc
	fi
fi
ay=($COMPILKIND)
if [ "`echo $COMPILKIND | egrep -wcs debug`" != "0"  ] && [ "`echo $COMPILKIND | egrep -wcs release`" != "0"  ]; then
	ay=("${ay[@]#debug}")
fi
if [ "`echo $COMPILKIND | egrep -wcs softfloat`" != "0"  ] && [ "`echo $COMPILKIND | egrep -wcs hardfloat`" != "0"  ]; then
	ay=("${ay[@]#softfloat}")
fi
if [ "`echo $COMPILKIND | egrep -wcs uclibc`" != "0"  ] && [ "`echo $COMPILKIND | egrep -wcs glibc`" != "0"  ]; then
	ay=("${ay[@]#uclibc}")
fi
COMPILKIND=`echo ${ay[@]}`
export COMPILKIND

SMP86XX_ROOTFS_PATH=$TOPDIR
if [ -z "$2" ]; then
	INSTALL_MOD_PATH=$SMP86XX_ROOTFS_PATH/build_mipsel/root
else
	INSTALL_MOD_PATH=$2
fi

BDAPP_DEVICE_TABLE=$SMP86XX_ROOTFS_PATH/target/generic/bdapp_device_table.txt

[ ! -f .tmpfile ] || rm -f .tmpfile
if [ "`echo "$COMPILKIND" | egrep -wos "codesourcery"`" = "codesourcery" ]; then
	if [ -z "$SMP86XX_TOOLCHAIN_PATH" ]; then
		SMP86XX_TOOLCHAIN_PATH=`which mips-linux-gnu-gcc | sed 's/\/\/*/\//g' | sed 's/\(.*\)\/bin\/mips-linux-gnu-gcc/\1/g'`
		if [ -z "$SMP86XX_TOOLCHAIN_PATH" ]; then
			SMP86XX_TOOLCHAIN_PATH=/utils/gcc/4.3.2/codesourcery/i386
		fi
	fi
	export SMP86XX_TOOLCHAIN_PATH
	if [ -z "$RMCFLAGS" ]; then
		RMCFLAGS="-DEM86XX_CHIP=EM86XX_CHIPID_TANGO3 -DEM86XX_MODE=EM86XX_MODEID_STANDALONE"
	fi
	export RMCFLAGS
        ay=(topdir)
        ay=(${ay[@]} smp86xx_toolchain_path smp86xx_rootfs_path install_mod_path compilkind bdapp_device_table)
        ay=("`echo ${ay[@]} | tr '[a-z]' '[A-Z]'`")
        apply_it export_to_config
	cp .tmpfile .tmpfile1
	export_to_config RMCFLAGS
	export_to_config PATH
	do_magic .tmpfile
	add_to_path_before /bin
	add_to_path_before /sbin
	add_to_path_before /usr/bin
	add_to_path_before /usr/sbin
	add_to_path_before /usr/local/bin
	add_to_path_before $SMP86XX_TOOLCHAIN_PATH/bin
	add_to_path_before $SMP86XX_ROOTFS_PATH/cross_rootfs/bin
	add_to_path_before $SMP86XX_ROOTFS_PATH/host/bin
	add_to_path_after PATH
	do_magic1 .tmpfile
else
        if [ ! -z "$SMP86XX_TOOLCHAIN_PATH" ]; then
		export_to_config SMP86XX_TOOLCHAIN_PATH
        fi
	export_to_config SMP86XX_ROOTFS_PATH
	export_to_config INSTALL_MOD_PATH
	export_to_config COMPILKIND
	if [ ! "$2" = "RMCFLAGS" ] ; then 
		mv .tmpfile $1
	else
		mv .tmpfile .makefile.in
	fi
fi
}

gen_make_rules
checkit 1 $*
case "$1" in
	.makefile.in )
		gen_make_path $*
	;;
       	rootfs-path* )
		if [ ! -f $1* ] ; then gen_rootfs-path_env $*; fi
	;;
       	make-rules* )
		if [ ! -z "$2" ]; then
			gen_make_path .makefile.in $2
		else
			gen_make_path .makefile.in mipsel
		fi
	;;
        * );;
esac
cd $TOPDIR
if [ -f .makefile.in ]; then
	cp .tmpfile1 rootfs-path.env
	do_magic2 evalpath
	add_to_path
	do_magic2 .tmpfile
	[ ! -f .tmpfile ] || rm -f .tmpfile
else
	echo "not happy here!!!!!!!!!!!!"
fi
