#!/bin/bash
# Build system helper functions
# M.Tyler 2013-5-16


. ./src/mtConf.txt
. ./src/apps_list.txt


MT_STARTUP()
{
	BCFILE=
	CONF=
	CWD=$(pwd)
	PKG_LIST=
	PRECONF=
	REMOVE=
	FLUSH_BUILD=

	cd ..

	PKG_REL=1

	if [ "$(whoami)" = "root" ]
	then
		echo
		echo "Error: You must NOT run this script as root."
		echo

		exit 1
	fi

	if echo "$CWD" | grep -q " "
	then
		echo
		echo "Error: Spaces not allowed in current working directory"
		echo

		exit 1
	fi

	cd "$CWD"
}


MT_check_pkg_name()
{
	if echo "$1" | grep -q " "
	then
		echo
		echo "Error: Spaces not allowed in a package name"
		echo

		exit 1
	fi

	APP=$(echo "$APPS_ALL" | awk -v APP="$1" '$1==APP { print $1 }')

	if [ "$APP" = "" ]
	then
		echo
		echo "Unknown option/package: $1"
		echo

		exit 1
	fi

	PKG_LIST="$PKG_LIST $1"
}


MT_PARSE_ARGS()
{
	while [ "$1" != "" ]
	do
		case "$1" in
		"all" )
			PKG_LIST=$(cat $CWD/etc/apps_list.tsv |
				awk -F "\t" '{ print $1 }' )
			;;

		"clean" )
			FLUSH_BUILD="Y"
			;;

		"flush" )
			echo Flushing directories.
			echo

			MT_flush_func

			MT_REMOVE_BCFILE

			exit
			;;

		"remove" )
			REMOVE=1
			;;

		"--bcfile" )
			shift
			BCFILE="$1"
			PKG_LIST=$(cat $BCFILE | awk '{ print $1 }' )
			;;

		"--conf" )
			shift
			CONF="$1"
			;;

		"--preconf" )
			shift
			PRECONF="$1"
			;;

		* )
			MT_check_pkg_name "$1"
			;;
		esac

		shift
	done
}


MT_CREATE_BCFILE()
{
	if [ "$BCFILE" != "" ]
	then
		return
	fi

	if [ "$PKG_LIST" = "" ]
	then
		PKG_LIST=$APPS
	fi

	BCFILE=bcfile.txt
	> $BCFILE

	for PKG in $PKG_LIST
	do
		printf "%s\t%s ./configure %s\n" "$PKG" "$PRECONF" "$CONF" >> $BCFILE
	done
}


MT_REMOVE_BCFILE()
{
	rm -vrf $CWD/bcfile.txt
}


MT_DISPLAY_INFO()
{
	cd $CWD
	cat $BCFILE | awk -F "\t" '{ printf "%-20s %s\n", $1, $2 }'

	UNDERLINE_TEXT "$1"

	printf "CWD           %s\n" $CWD
	printf "PKG_REL       %s\n" $PKG_REL
	echo

	if [ "$REMOVE" != "" ]
	then
		UNDERLINE_TEXT "*** REMOVING PACKAGES ***"
	fi

	echo Press ENTER to continue...
	echo

	read JUNK
}


MT_GET_PKG_DIR()
{
	PKG_DIR=$(cat $CWD/etc/apps_list.tsv |
		awk -F "\t" -v PKG="$1" '$1 == PKG { print $2; exit }' )
}


MT_ACTION_BUILD()
{
	if [ "$REMOVE" != "" ]
	then
		MT_remove_func

		if [ "$FLUSH_BUILD" != "" ]
		then
			MT_flush_func
			MT_REMOVE_BCFILE
		fi

		return
	fi

	for PKG in $PKG_LIST
	do
		# Get the last directory with this package name prefix
		cd $CWD/..

		MT_GET_PKG_DIR "$PKG"
		SRC_DIR=$PKG_DIR

		SRC_VER=$(cat $CWD/../VERSION)
		SRC_VER=$(echo $SRC_VER | sed "s/_/./g" | sed "s/[^0-9.]//g")

		cd $CWD

		CONF=$(cat "$BCFILE" |
			awk -F "\t" -v PKG="$PKG" '$1==PKG { print $2; exit }')

#		Caller uses: PKG, CONF, SRC_DIR, SRC_VER
		MT_build_app_func

		if [ "$FLUSH_BUILD" != "" ]
		then
			MT_flush_func
		fi
	done
}


MT_RUN_COM()
{
	TMPFILE=_TMP.sh

	echo $* > $TMPFILE
	chmod a+x $TMPFILE
	cat $TMPFILE

	./$TMPFILE
	RES=$?
	rm $TMPFILE

	if [ "$RES" != "0" ]
	then
		echo Error!
		exit 1
	fi
}

