#!/bin/sh

modulename=taskmonitor
file=/sys/kernel/debug/taskmonitor

if modprobe $modulename target="-1" 2> /dev/null; then
	echo "Should throw an error with an invalid pid"
	exit 1
fi

printf "%s" '
#include <math.h>
#include <stdlib.h>

int main() {
	double acc = 0;
	for (int i = 0; i < 1000000000; i++) {
		acc += sqrt((double)random());
	}
	return acc;
}
' > stress.c

if ! gcc -o stress stress.c -lm; then
	echo "failed to compile user program"
	echo "please contact lkp@os.rwth-aachen.de"
	exit 1
fi

./stress &

pid=$!
if ! modprobe $modulename target=$pid; then
	echo "Could not load module $modulename.ko!"
	exit 1
fi

if ! [ -f "$file" ]; then
	echo "$file not created!"
	exit 1
fi

## The line below is executed by the LKP Maintainers CI. HIDDEN replaces the real value the CI uses.
# sleep HIDDEN
if ! output=$(grep -oP 'usr \K[0-9]+' $file); then
	echo "error while accessing $file"
	exit 1
fi
if ! nb=$(wc -l $file | cut -f 1 -d ' '); then
	echo "error while accessing $file"
	exit 1
fi

# check that the number of lines produced is somewhat similar to the amount of seconds we slept
# if [ -n "$nb" ] && [ "$nb" -ne 9 ] && [ "$nb" -ne 10 ] && [ "$nb" -ne 11  ]; then
# 	echo "$file contains an unexpected number of lines!"
# 	exit 1
# fi

# check that the usr time are increasing
prev=0
for val in $output; do
	if [ "$val" -le "$prev" ]; then
		echo "Error, usr times are wrong!"
		exit 1
	fi
	prev=$val
done


# test the we are not crashing the kernel by writing to the debugfs
echo "anything" > "$file" 2>/dev/null


if ! rmmod $modulename; then
	echo "Fail while unloading module"
	exit 1
fi

echo scan > /sys/kernel/debug/kmemleak
sleep 60
cat /sys/kernel/debug/kmemleak
