#!/bin/sh
# - testtime
# - class
# - nr_threads
# - test

mount_dev()
{
	local mnt=/mnt/stress-ng

	[ $nr_partitions -ge 1 ] || die "nr_partitions is less than 1"
	partition=${partitions%% *}
	if [ "$test" = "verity" ]; then
		log_cmd umount $partition
		log_cmd mkfs.$fs -q -F -O verity $partition || die "fail to mkfs.$fs -q -F -O verity $partition"
	fi

	log_cmd mkdir -p $mnt
	log_cmd mount $partition $mnt 2>/dev/null
	cd $mnt
}

## some options are universal, put them in universal_setting
set_for_universal()
{

	[ -n "$testtime" ] || testtime=1

	default_option="
		--timeout $testtime \
		--times \
		--verify \
		--metrics-brief
	"

	## stressors spawn exec can't run as root
	## all classes need to exclud them except class exec_spawn
	default_exclude="spawn,exec"

	# Fix stress-ng: error: [36360] process [36390] (stress-ng-swap) aborted early, out of system resources
	[ $(nproc) -gt 16 ] && default_exclude="$default_exclude,swap"
}

# some class need special settinf
set_for_class()
{
	case "$class" in
	"memory")
		stress_opts="--minimize"
		exclude_stress=",stack"
		;;
	"os")
		stress_opts="--minimize"
		mount_dev
		;;
	"filesystem"|"interrupt"|"io")
		mount_dev
		;;
	"vm")
		cd ${mount_points%% *}
		;;
	*)
		;;
	esac
}

run_test()
{
	## most stressors could run as root except exec and spawn,
	## classify exec and spawn into exec_spawn, run it as lkp.
	## run other stress-ng as root
	## use option --exclude to ignore spawn and exec.
	[ -n "$test" ] && {
		if [ "$test" = "ping-sock" ]; then
			log_cmd sysctl -w net.ipv4.ping_group_range="0 $nr_threads"
		fi

		test="--$test"
		if [ "$class" = "exec_spawn" ]; then
			mkdir /home/lkp && chown -R lkp:lkp /home/lkp
			log_cmd su - lkp -s /bin/bash -c "stress-ng --timeout $testtime --times --verify --metrics-brief $test $nr_threads 2>&1"
		else
			log_cmd stress-ng $default_option $test $nr_threads 2>&1
		fi
		return
	}

	log_cmd stress-ng \
		$default_option \
		--sequential $nr_threads \
		--class $class $stress_opts \
		--exclude $default_exclude$exclude_stress 2>&1
}

set_for_universal
set_for_class
sleep 2
run_test
exit_value=$?

exit $exit_value
