#!/bin/bash -p

# Note: STAGING_DIR is the <buildroot>/output/staging generated from the "make buildroot" for PiBox.
if [ "$STAGING" != "" ] 
then
	export STAGING_DIR=$STAGING
else
	if [ "$BR" != "" ] 
	then
		export STAGING_DIR=$BR/output/staging
	else
		echo "You must set BR to the top of your buildroot tree or STAGING to where the staging tree lives."
		exit 1
	fi
fi

# Toolchain should be the toolchain built with PiBox and installed as an RPM.
if [ "$TC" != "" ] 
then
	export TOOLCHAIN=$TC
else
	echo "You must set TC to where the cross toolchain lives."
	exit 1
fi

# Need to specify where the opkg tools are installed.
# if [ "$OPKG_DIR" = "" ] 
# then
# 	echo "You must set OPKG_DIR to where the opkg-build program lives."
# 	exit 1
# fi

# if [ -f config.log ]
# then
# 	make distclean
# fi

PREFIX=arm-unknown-linux-gnueabi

echo "Toolchain   : $TOOLCHAIN"
echo "Staging tree: $STAGING_DIR"
echo "Prefix      : $PREFIX"

# autoreconf -i

export PATH=$TOOLCHAIN/bin:$TOOLCHAIN/$PREFIX/bin:$PATH

	CFLAGS=-I$STAGING_DIR/usr/include \
	LDFLAGS="-L$STAGING_DIR/usr/lib -L$STAGING_DIR/lib --sysroot=$STAGING_DIR/" \
	CC=$PREFIX-gcc \
	./configure \
		--with-path=$TOOLCHAIN/bin:$TOOLCHAIN/$PREFIX/bin:$PATH \
		--enable-force-shutdown \
		--enable-ignore-busy \
		--host=arm-unknown-linux-gnueabi \
		--build=`uname -m`

PATH=$TOOLCHAIN/bin:$PATH \
	CFLAGS=-I$STAGING_DIR/usr/include \
	LDFLAGS="-L$STAGING_DIR/usr/lib -L$STAGING_DIR/lib --sysroot=$STAGING_DIR/" \
	make 

exit 0

OPKG_DIR=$OPKG_DIR DESTDIR=`pwd`/install make install pkg

echo 
echo "----------------------------------------------"
echo "opkg has been built under the opkg directory:"
echo "----------------------------------------------"
echo 
ls -l opkg/*.opk
