#!/bin/sh


#initialization

tmp="/tmp";
if [ -z "$MEMSTICK_ROOT" ] ; then
	MEMSTICK_ROOT=/mnt/memstick
fi;

if [ $# -lt 2 ] ; then
	echo "Usage $0 <newversion> <prevversion>";
	exit 2;
fi;
newtag=tekkotsu-`echo $1 | tr . _`;
oldtag=tekkotsu-`echo $2 | tr . _`;

echo New tag: ${newtag}
echo Old tag: ${oldtag}



#cvs export source

cd ${tmp};
rm -rf Tekkotsu_$1
rm -rf Tekkotsu_$1.tar.gz
rm -rf Tekkotsu_memstick_$1
rm -rf Tekkotsu_memstick_$1.tar.gz

cvs export -r ${newtag} -d Tekkotsu_$1 Tekkotsu
if [ ! -d Tekkotsu_$1 ] ; then
	echo "cvs export failed"
	exit 1;
fi;



#build source tarball

cd Tekkotsu_$1;

#if [ `grep -c default.tm project/ms/config/tekkotsu.cfg` -gt 0 ] ; then
#	echo "You forgot to switch the thresholds file to the more general ball one";
#	exit 1;
#fi;

if [ `grep PROJECT_NUMBER docs/doxygencfg | grep -c $1` -eq 0 ] ; then
	echo "Version mismatch with docs/doxygencfg - you forgot to update PROJECT_NUMBER";
	exit 1;
fi;

for x in project/SampleMC.h project/SampleBehavior.h ; do
	if [ -d "$x" ] ; then
		echo "You forgot to untag the sample file"
		exit 1;
	fi;
done;

curt=`date +%Y%m%d%H%M`;
find project/ms -exec touch -ft $curt \{\} \; ;

cd ${tmp};
tar -cvzf Tekkotsu_$1.tar.gz Tekkotsu_$1;



#build memstick image tarball

cd Tekkotsu_$1;
cd project;

export TEKKOTSU_ROOT=..

for x in TGT_ERS210 TGT_ERS220 TGT_ERS2xx ; do
	echo $x > ${TEKKOTSU_ROOT}/TARGET_MODEL;
	printf "\n\nTesting $x build\n\n\n";
	gmake clean
	if [ $? -ne 0 ] ; then
		echo "Framework clean failed"
		exit 1;
	fi;
	gmake;
	if [ $? -ne 0 ] ; then
		echo "Framework Build failed"
		exit 1;
	fi;
done;

echo "Enter memstick to be built onto - this memstick will be erased";
mntmem $MEMSTICK_ROOT;
rm -rf /mnt/memstick;
gmake update;
if [ $? -ne 0 ] ; then
	echo "Project build failed"
	exit 1;
fi;

mntmem $MEMSTICK_ROOT;
cp -arp /mnt/memstick ${tmp}/Tekkotsu_memstick_$1;
umntmem $MEMSTICK_ROOT;
chmod a+rx ${tmp}/Tekkotsu_memstick_$1

cd ${tmp};
tar -cvzf Tekkotsu_memstick_$1.tar.gz Tekkotsu_memstick_$1;

echo "Build done - don't forget to double check the image actually works"



#build TekkotsuMon tarball

cd ${tmp};
cp -r Tekkotsu_$1/tools/mon Tekkotsu_mon_$1;
tar -czvf Tekkotsu_mon_$1.tar.gz Tekkotsu_mon_$1;



#build patch file

cd ${tmp}
cvs rdiff -r ${oldtag} -r ${newtag} AiboPup > Tekkotsu_patch_$2_to_$1.diff;



#build documentation

cd ${tmp}/Tekkotsu_$1;
docs/builddocs -a -c -r -s -t;
cd docs/generated;
mv html Tekkotsu_doc_$1;
tar -cvzf Tekkotsu_doc_$1.tar.gz --exclude Tekkotsu_doc_$1/search.idx Tekkotsu_doc_$1;
mv Tekkotsu_doc_$1.tar.gz ${tmp};



#final notice

echo "Done!"
echo ""
echo "If you disabled robot access on the staging website, don't forget to"
echo "turn it back on!"
