#!/bin/bash -f

# Build lowmem exhaustion/corruption tester

# Copyright (C) 2003-2006 IBM
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.


# How much RAM do we have?
RAM=`cat /proc/meminfo | grep MemTotal | awk -F " " '{print $2}'`
SPACE_REQUIRED=`expr $RAM \* 2`

# Do we have enough space?
MEMTESTDIR="$POUNDER_TMPDIR/memtest/"
rm -rf "$MEMTESTDIR"
mkdir -p "$MEMTESTDIR"
FREE_SPACE=`df -k -P "$MEMTESTDIR" | tail -n 1 | awk -F " " '{print $4}'`
if [ "$FREE_SPACE" -lt "$SPACE_REQUIRED" ]; then
        echo "[memtest] Insufficient space. Free space: $FREE_SPACE kB. Space required: $SPACE_REQUIRED kB. Not building memtest."
        exit -1
fi

cd "$POUNDER_OPTDIR"

# Download a script and parse out the junk we don't want.
if [ ! -f "memtest.sh" ]; then
	if [ $USE_CACHE -eq 1 ]; then
		wget "${POUNDER_CACHE}memtest.shtml"
	fi
	if [ ! -f "memtest.shtml" ]; then
		wget "http://people.redhat.com/dledford/memtest.shtml"
	fi
	IN_BLOCK=0

	if [ ! -f "memtest.shtml" ]; then
		echo "[memtest] Could not download memtest.shtml.  Aborting!"
		exit -1
	fi

	(cat memtest.shtml | while read f; do
		echo "$f" | grep -q BLOCKQUOTE
		if [ "$?" -eq 0 ]; then
			if [ "$IN_BLOCK" -eq 0 ]; then
				IN_BLOCK=1
			else
				IN_BLOCK=0
			fi
		else
			if [ "$IN_BLOCK" -eq 1 ]; then
				echo "$f"
			fi
		fi
	done) | sed -e 's/\/bin\/bash2/\/bin\/bash/g' > memtest.sh
	chmod a+x memtest.sh
	patch -p0 < "$POUNDER_SRCDIR/memtest.patch"
	rm -rf memtest.shtml
fi