#!/bin/sh

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

pid=$$

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

sleep 5
val="$(dmesg | grep -c "pid $pid" )"
if [ "$val" -lt 5 ] || [ "$val" -gt 7 ]; then
	echo "didn't count the correct amount of dmesg lines ($val instead of 5)"
	exit 1
fi

if ! pgrep monitor_fn ; then
	echo "monitor_fn kthread not created!"
	exit 1
fi

if ! printf stop > /sys/kernel/$modulename; then
	echo "could not write to /sys/kernel/$modulename"
fi

if pgrep monitor_fn ; then
	echo "monitor_fn kthread still here!"
	echo "it should be stopped after \"printf stop > /sys/kernel/$modulename\""
	exit 1
fi

sleep 5
val="$(dmesg | grep -c "pid $pid" )"
if [ "$val" -lt 5 ] || [ "$val" -gt 7 ]; then
	echo "incorrect amount of logs: should be 5 instead of $val"
	exit 1
fi
sys1=$(awk '{print $NF}' /sys/kernel/$modulename )


# check that only one kthread is created even after writing many "start"
for _ in 0 1 2 3 4 5; do
	if ! printf start > /sys/kernel/$modulename; then
		echo "could not write to /sys/kernel/$modulename"
		exit 1
	fi
done

if [ "$(pgrep monitor_fn | grep -Ec ".")" -gt 1 ] ; then
	echo "too many kthread present!"
	echo "no more than 1 kthread should be running"
	exit 1
fi

sleep 3
val="$(dmesg | grep -c "pid $pid" )"
if [ "$val" -lt 8 ] || [ "$val" -gt 10 ]; then
	echo "incorrect amount of logs: should be 8 instead of $val"
	exit 1
fi
sys2=$(awk '{print $NF}' /sys/kernel/$modulename )

if [ "$sys1" -gt "$sys2" ]; then
	echo "sys time was not updated"
	echo "$sys1 $sys2"
	exit 1
fi

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