#!/bin/bash
# SPDX-License-Identifier: GPL-2.0

bindir=$(dirname "$0")
cd "$bindir" || exit 1

# lint first
./flake8.sh || exit 1

# not every test require sudo permission, but let's enforce it here.
if [ "$EUID" -ne 0 ]
then
	echo "Run as root"
	exit 1
fi

# Stop any stale DAMON from previous tests
../../damo stop 2>/dev/null

restart_damon_stat="false"
damon_stat_enabled_file="/sys/module/damon_stat/parameters/enabled"
if [ -f "$damon_stat_enabled_file" ] && \
	[ $(cat "$damon_stat_enabled_file") = "Y" ]
then
	echo "DAMON_STAT is running.  Disable for testing."
	echo N > "$damon_stat_enabled_file"
	restart_damon_stat="true"
fi

for test_dir in unit pre-commit args_damon record report schemes \
	damon_reclaim damon_lru_sort start_stop
do
	if ! "./$test_dir/test.sh"
	then
		if [ "$restart_damon_stat" = "true" ]
		then
			echo Y > "$damon_stat_enabled_file"
		fi
		exit 1
	fi
done

if [ "$restart_damon_stat" = "true" ]
then
	echo Y > "$damon_stat_enabled_file"
fi

echo "PASS ALL"
