#!/bin/bash
# libmicro installer
P=libmicro-smallbatches-install
DEFAULT_VERSION=1
. $SHELLPACK_INCLUDE/common.sh
TIME_CMD=`which time`
if [ "$TIME_CMD" = "" ]; then
        TIMEFORMAT="%2Uuser %2Ssystem %Relapsed %P%%CPU"
        TIME_CMD="time"
fi
HG_LOCATION=https://hg.java.net/hg/libmicro~hg-repo
MIRROR_LOCATION="$WEBROOT/libmicro"

install-depends gcc

# Basic argument parser
TASKSET_SERVER=
TASKSET_CLIENT=
SERVERSIDE_COMMAND=none
SERVERSIDE_NAME=`date +%Y%m%d-%H%M-%S`

while [ "$1" != "" ]; do
	case "$1" in
	-v)
		VERSION=$2
		shift 2
		;;
	--serverside-command)
		SERVERSIDE_COMMAND=$2
		shift 2
		;;
	--serverside-name)
		SERVERSIDE_NAME=$2
		shift 2
		;;
	*)
		echo Unrecognised option: $1
		shift
	esac
done
if [ "$TASKSET_SERVER" != "" ]; then
	echo TASKSET_SERVER: $TASKSET_SERVER
	echo TASKSET_CLIENT: $TASKSET_CLIENT
fi
if [ -z "$VERSION" ]; then
	VERSION=$DEFAULT_VERSION
fi

# Unconditionally fetch the tar to find out the real version number
TARFILE=libmicro-smallbatches-${VERSION}.tar.gz
hg_fetch $HG_LOCATION libmicro-smallbatches-${VERSION}-installed $MIRROR_LOCATION/$TARFILE $SHELLPACK_SOURCES/$TARFILE
cd $SHELLPACK_SOURCES
tar -xf $TARFILE
if [ $? -ne 0 ]; then
	error "$P: tar xf libmicro-smallbatches-${VERSION}.tar.gz failed"
	popd > /dev/null
	exit $SHELLPACK_ERROR
fi

# Rename directory to something we expect.
DST_DIR=`tar tf $TARFILE | head -n 1 | awk -F / '{print $1}'`
mv $DST_DIR libmicro-smallbatches-${VERSION}-installed
pushd libmicro-smallbatches-${VERSION}-installed > /dev/null || die Failed to rename tar

pushd $SHELLPACK_SOURCES/libmicro-smallbatches-${VERSION}-installed || die Failed to change to source directory
for FILE in `find -name "*"`; do
	touch $FILE
done

echo '--- Makefile.com.orig	2014-03-31 12:09:53.689008589 +0100
+++ Makefile.com	2014-03-31 12:09:57.317989834 +0100
@@ -107,7 +107,7 @@
 	echo "char compiler_version[] = \""`$(COMPILER_VERSION_CMD)`"\";" > tattle.h
 	echo "char CC[] = \""$(CC)"\";" >> tattle.h
 	echo "char extra_compiler_flags[] = \""$(extra_CFLAGS)"\";" >> tattle.h
-	$(CC) -o tattle $(CFLAGS) -I. ../tattle.c libmicro.a -lrt -lm
+	$(CC) -o tattle $(CFLAGS) -I. ../tattle.c libmicro.a -lrt -lm -lpthread
 
 $(ELIDED_BENCHMARKS):	../elided.c
 	$(CC) -o $(@) ../elided.c' | patch -p0

make clean
if [ $? -ne 0 ]; then
	error "$P: make clean failed"
	popd > /dev/null
	exit $SHELLPACK_ERROR
fi
make -j$NUMCPUS 
if [ $? -ne 0 ]; then
	make -j$NUMCPUS 
	if [ $? -ne 0 ]; then
		error "$P: make failed"
		popd > /dev/null
		exit $SHELLPACK_ERROR
	fi
fi

echo libmicro installed successfully
#### Description libmicro-smallbatches
#### Details libmicro-smallbatches 5
