# -*- shell-script -*-

FUNCTIONS_DIR=debian/tests/functions.d

match_or_exit() {
	file_to_match=$1
	pattern_file=$2

	while read line_to_match <&3 && read pattern_line <&4; do
		if [ "${line_to_match##$pattern_line}" ]; then
			echo '!!! MISMATCH !!!' >&2
			echo "Line:    $line_to_match" >&2
			echo "Pattern: $pattern_line" >&2
			exit 1
		fi
	done 3<"$file_to_match" 4<"$pattern_file"
}

# configure for deterministic testing
patch_service_for_test_and_restart() {
	test -c /dev/hwrng || {
		echo '~~~ /dev/hwrng does not exist, skipping test'
		exit 77
	}
	echo '~~~ Configure rngd so that /dev/hwrng is used'
	echo 'HRNGDEVICE=/dev/hwrng' >/etc/default/rng-tools-debian
	echo '~~~ Restart service'
	systemctl restart rng-tools-debian.service
}

query_systemd_for_service_status() {
	echo '~~~ Query systemd for service status'
	systemctl status rng-tools-debian.service | tee status.out
	echo '~~~ Grep loaded and active status'
	grep 'Loaded: loaded' status.out
	grep 'Active: active (running)' status.out
}

query_journal_and_check_the_logs() {
	echo '~~~ Query journal for logs related to the service'
	journalctl -b -u rng-tools-debian.service | tail -n4 | tee start.out
	match_or_exit start.out "$FUNCTIONS_DIR/start.patterns"
}

run_rngtest_and_check_the_result() {
	echo '~~~ Run rngtest against the kernel (via /dev/random)'
	rngtest -c 10 </dev/random 2>&1 | tee rngtest.out
	match_or_exit rngtest.out "$FUNCTIONS_DIR/rngtest.patterns"
}

stop_service_and_check_the_logs() {
	echo '~~~ Stop service and check logs related to the service'
	systemctl stop rng-tools-debian.service
	journalctl -b -u rng-tools-debian.service | \
	    tail -n19 | grep -Fv 'Stopping' | tee stop.out
	match_or_exit stop.out "$FUNCTIONS_DIR/stop.patterns"
}
