#!/bin/bash
# mutilate installer
P=mutilate-install
DEFAULT_VERSION=1
. $SHELLPACK_INCLUDE/common.sh
GIT_LOCATION=git://github.com/leverich/mutilate.git
MIRROR_LOCATION="$WEBROOT/mutilate"

install-depends libevent-devel gengetopt zeromq-devel gcc-c++ scons

# Basic argument parser
while [ "$1" != "" ]; do
	case "$1" in
	-v)
		VERSION=$2
		shift 2
		;;
	*)
		echo Unrecognised option: $1
		shift
	esac
done
if [ -z "$VERSION" ]; then
	VERSION=$DEFAULT_VERSION
fi

# Unconditionally fetch the tar to find out the real version number
TARFILE=mutilate-${VERSION}.tar.gz
git_fetch $GIT_LOCATION mutilate-${VERSION} $MIRROR_LOCATION/$TARFILE $SHELLPACK_SOURCES/$TARFILE
cd $SHELLPACK_SOURCES
tar -xf $TARFILE
if [ $? -ne 0 ]; then
        error "$P: tar xf mutilate-${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 mutilate-${VERSION}
pushd mutilate-${VERSION} > /dev/null || die Failed to rename tar

pushd $SHELLPACK_SOURCES/mutilate-${VERSION} || die Failed to change to source directory

# Workaround a time bug, not obvious why event_base cached time lookup returned
# really stupid values
echo "diff --git a/mutilate.cc b/mutilate.cc
index cacf4db..af7f734 100644
--- a/mutilate.cc
+++ b/mutilate.cc
@@ -942,7 +942,7 @@ void do_mutilate(const vector<string>& servers, options_t& options,
     //    now = get_time();
     //#else
     struct timeval now_tv;
-    event_base_gettimeofday_cached(base, &now_tv);
+    gettimeofday(&now_tv, NULL);
     now = tv_to_double(&now_tv);
     //#endif" | patch -p1 || exit $SHELLPACK_ERROR
 
scons || exit $SHELLPACK_ERROR
mkdir -p ../mutilate-${VERSION}-installed/bin
cp mutilate ../mutilate-${VERSION}-installed/bin

echo mutilate installed successfully
#### Description mutilate
#### Details mutilate 16
