#!/bin/bash
# This is the script to install the lockmemter programs
#

. /etc/autobench.conf || . functions

WEB_LOCATION="ftp://oss.sgi.com/projects/lockmeter/download/lockstat-1.4.10.tar.gz"
WEB_PATCH_LOCATION="ftp://oss.sgi.com/projects/lockmeter/download/v2.5/lockmeter1.5-2.5.17.diff.gz"
. $AUTODIR/var/server-repository

wget -q -O $AUTODIR/sources/lockstat-latest.tar.gz $SERVER_REPO/sources/lockstat-latest.tar.gz
if [ $? -ne 0 ]; then 
  # Didn't find it on the repo, try the web location
  echo "Fetching from the network"
  wget -q -O $AUTODIR/sources/lockstat-latest.tar.gz $WEB_LOCATION
  if [ $? -ne 0 ]; then
    # Couldn't get the source -- complain
    echo "WARNING: could not download the source for lockstat"
    exit 1
  fi
fi

# Uncompress it
pushd $AUTODIR/sources > /dev/null
rm -rf lockstat 2> /dev/null
tar zxf lockstat-latest.tar.gz

# Find the patched kernel to build against
KERN_LOC=`find /usr/src -name lockmeter.h`
if [ -z "$KERN_LOC" ]; then
  KERN_LOC=`find $TMPDIR -name lockmeter.h`
  if [ -z "$KERN_LOC" ]; then

	# Couldn't find the header file locally, download it.
	wget -q -O $AUTODIR/sources/lockstat/patch-latest.gz $SERVER_REPO/sources/lockstat-latest.patch.gz
	if [ $? -ne 0 ]; then 
	  # Didn't find it on the repo, try the web location
	  echo "Fetching patch from the network"
	  wget -q -O $AUTODIR/sources/lockstat/patch-latest.gz $WEB_PATCH_LOCATION
	  if [ $? -ne 0 ]; then
	    # Couldn't get the source -- complain
	    echo "WARNING: could not download the patch for lockstat"
	    exit 2
	  fi
	fi
    # This is an ugly hack.  We've got a diff file, and we want just one file
    # from it...
	mkdir $AUTODIR/sources/lockstat/linux
    OFFSETS=`zcat $AUTODIR/sources/lockstat/patch-latest.gz | \
    	grep -n -A 1 "^+++.*linux/lockmeter.h" | \
		tail -n 1 | \
		sed -e "s/^\([0-9][0-9]*\).*[^0-9]\([0-9][0-9]*\) @@$/\1 \2/"`
    START=`echo $OFFSETS | cut -f1 -d" "`
    START=$(($START+1))
    LENGTH=`echo $OFFSETS | cut -f2 -d" "`
    zcat $AUTODIR/sources/lockstat/patch-latest.gz | tail +$START | \
		head -n $LENGTH | sed -e "s/^+//" \
		> $AUTODIR/sources/lockstat/linux/lockmeter.h
	export LINUX_INC_ROOT="."
  fi
fi

pushd lockstat > /dev/null
if [ -n "$KERN_LOC" ]; then
	export LINUX_INC_ROOT=`echo $KERN_LOC | head -n 1 | sed -e "s/include.*$/include/"`
fi
make
popd > /dev/null

popd > /dev/null
