#!/bin/sh -ef
# NAME=HDD array stress
# DESCRIPTION=HDD array stress test
# DESTROYS_HDD=true
# IS_INTERACTIVE=false
# POWEROFF_DURING_TEST=false
# VERSION=0.1
# TAGS=hdd,stress
# DEPENDS=CPU,HDD,Memory,Mainboard,Disk Controller
# VAR=TESTTIME:int:3600:Total time of HDD array testing, sec
# VAR=LOGTIME:int:120:Time between progress updates, sec
# VAR=JOBS:int:16:Number of parallely running jobs during compile
# VAR=STRESS_TREE:string:linux-2.6.22.5-31-stress.tar.gz:Tarball file containing stress test tree

. /usr/share/inquisitor/functions-test

clear_testing_environment()
{
	cd $HOME
	umount -f $MOUNTPOINT >$DEBUG_TTY 2>&1 || true
}

exit_handler()
{
	clear_testing_environment
	[ -d "$MOUNTPOINT" ] && rmdir $MOUNTPOINT
}

MOUNTPOINT=`mktemp -d`

array_stress_check()
{
	local array=$1

	echo -n "Preparing array $array..."
	prepare_array_for_test $array
	echo_success

	echo "Testing $array..."
	START=`date "+%s"`
	LAST_LOGTIME=$TOTAL_START

	while true; do
		TIME=`date "+%s"`
		if [ $(($TIME - $START)) -gt $TIME_PER_ARRAY ]; then
			clear_testing_environment
			break
		else
			make clean >$DEBUG_TTY 2>&1 &&
			make -j $JOBS >$DEBUG_TTY 2>&1 ||
			test_failed "Make error"
		fi

		if [ $(($TIME - $LAST_LOGTIME)) -gt $LOGTIME ]; then
			test_progress $(( $TIME - $START )) $TESTTIME
			LAST_LOGTIME=$TIME
		fi
	done
}

prepare_array_for_test()
{
	local array=$1

	mke2fs -m0 -F $array >$DEBUG_TTY 2>&1 || test_failed "Disk write error"
	mount -t ext2 $array $MOUNTPOINT

	cd "$SHARE_DIR"
	tar xvf "$STRESS_TREE" -C "$MOUNTPOINT" >$DEBUG_TTY 2>&1 || test_failed "Untaring error"

	cd $MOUNTPOINT
	tree_name=`basename "$STRESS_TREE" .tar.gz`
	cd $tree_name

	# Is it linux source?
	if echo "$tree_name" | grep '^linux' ; then
		find . -print | xargs touch >/dev/null 2>&1 || true
		touch .config include/linux/autoconf.h >/dev/null 2>&1 || true
	fi
}

# Making arrays
if raid-wizard-optimal; then
	sleep 10
	HDD_QUANTITY=`get_harddrives_list | wc -l`
	if [ "$HDD_QUANTITY" -eq 0 ]; then
		test_succeeded "No HDDs"
		exit 0
	fi
	TIME_PER_ARRAY=$(( $TESTTIME / $HDD_QUANTITY ))

	# TEMPORARY checking for correct number of JOBS
	TOTAL_MEMORY=$(( `grep MemTotal /proc/meminfo | awk '{print $2}'` / 1024 ))
	[ "$TOTAL_MEMORY" -lt 512 ] && JOBS=4 || true

	TOTAL_START=`date "+%s"`
	test_promise_time $TESTTIME

	for i in `get_harddrives_list`; do
		array_stress_check $i
	done

	test_succeeded
else
	test_failed "Optimal array creation error"
fi
