#!/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

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

if [ "$(ls /sys/kernel/debug/shrinker/ | grep taskmonitor | wc -l)" != 1 ]; then
	ls /sys/kernel/debug/shrinker/ | grep taskmonitor
	echo "No shrinker found or too many shrinker found!"
	exit 1
fi

shrinker="/sys/kernel/debug/shrinker/$(ls /sys/kernel/debug/shrinker/ | grep taskmonitor)"

if ! [ -e  "$shrinker" ]; then
	echo "Shrinker folder not found! $shrinker"
	exit 1
fi

sleep 17

if ! first=$(awk '{print $NF}' "$shrinker"/count ); then
	echo "Failed to read $shrinker/count"
	exit 1
fi

if ! echo "0 0 $((first - 2))" > "$shrinker"/scan; then
	echo "Failed to write to $shrinker/scan"
	exit 1
fi

if ! second=$(awk '{print $NF}' "$shrinker"/count ); then
	echo "Failed to read to $shrinker"
	exit 1
fi

sleep 2

if ! third=$(awk '{print $NF}' "$shrinker"/count ); then
	echo "Failed to read to $shrinker"
	exit 1
fi

if [ -z "$first" ] || [ -z "$second" ] || [ -z "$third" ]; then
	echo "Problem while using the shrinker's count function"
	exit 1
fi

if [ "$second" -ge "$third" ] || [ "$third" -ge "$first" ]; then
	echo "Shrinker failed: the shrinker did not manage to free memory"
	exit 1
fi

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
