#!/bin/sh

set -e

cwd=`pwd`
target=""
ret_value=0

# build up our list of targets
for i; do
	case $1 in
		--native) environment=native; shift;;
#		--cross)  environment=cross; shift;;
		--compile) target="all"; shift;;
		--clean) target="clean"; shift;;
		--install) target="install"; shift;;
	esac
	if [ $# -eq 0 ]
	then
		break
	fi
done

architecture=`dpkg-architecture -qDEB_HOST_ARCH`

echo "***********************************"
echo "architecture[$architecture]..environment[$environment]..target[$target]"
echo "***********************************"


touch makedirs.$$

# create our file lists
find . -name "Makefile" -print >> makedirs.$$
awk '{ print substr($0, 0, index($0, "Makefile")-1) }' makedirs.$$ > dirslist.$$

# create .obj and .dep directories
for file in $(cat dirslist.$$)
do
        mkdir -p ${file}/.obj
        touch ${file}/.obj/.gitignore
        mkdir -p ${file}/.dep
        touch ${file}/.dep/.gitignore
done

mkdir -p lib/libcutils/.obj/arch-arm
mkdir -p lib/libcutils/.obj/arch-x86

touch lib/libcutils/.obj/arch-arm/.gitignore
touch lib/libcutils/.obj/arch-x86/.gitignore

mkdir -p lib/libcutils/.dep/arch-arm
mkdir -p lib/libcutils/.dep/arch-x86

rm -fr makedirs.$$ dirslist.$$

# do we have any targets to execute on?
if [ V"$target" != V ]
then
	# single or multiple libraries?
	if [ -d lib -a -e lib/Makefile ]
	then
		echo "*******************************************"
		echo "build-component.sh MAKE ARCH=$architecture -C $cwd/lib $target"
		echo "*******************************************"
		make ARCH=$architecture -C $cwd/lib $target
		ret_value=$?
	elif [ -d lib ]
	then
		echo "********************************************"
		echo "build-component.sh lib/build-tree.sh $environment $target"
		echo "********************************************"
		cd lib
		./build-tree.sh $environment $target
		ret_value=$?
		cd ..
	fi
	if [ $ret_value -eq 0 ]
	then
		# single or multiple applications?
		if [ -d app -a -e app/Makefile ]
		then
			echo "*******************************************"
			echo "build-component.sh MAKE ARCH=$architecture -C $cwd/app $target"
			echo "*******************************************"
			make ARCH=$architecture -C $cwd/app $target
			ret_value=$?
		elif [ -d app ]
		then
			echo "********************************************"
			echo "build-component.sh app/build-tree.sh $environment $target"
			echo "********************************************"
			cd app
			./build-tree.sh $environment $target
			ret_value=$?
			cd ..
		fi
	fi

	if [ $ret_value -eq 0 ]
	then
		if [ "$target" = "install" -a -d $cwd/../data ]
		then
			PKG_NAME=`cat pkg_name`
			echo "********************************************"
			echo "build-component.sh INSTALLING data directory"
			echo "********************************************"
			mkdir -p $cwd/debian/$PKG_NAME/usr/local/share/motorola/$PKG_NAME
			cp -fa $cwd/../data/* $cwd/debian/$PKG_NAME/usr/local/share/motorola/$PKG_NAME
			ret_value=$?
		fi
	fi
fi

exit $ret_value
