#!/bin/sh
set -eu

TUNED_LOGFILE=/var/log/tuned/tuned.log

# Function to get cpu latency from the TuneD log file
get_cpu_latency(){
	grep "setting new cpu latency" ${TUNED_LOGFILE} \
		| rev | cut -d " " -f1 | rev | tail -1
}

# If it is running on s390x expect an error
check_arch(){
	arch=$(uname -i)
	if [ "$arch" = "s390x" ]; then
		grep "PM_QoS control is not supported in s390x" ${TUNED_LOGFILE}
		if [ $? -eq 0 ]; then
			exit 0
		else
			exit 1
		fi
	fi
}

# Create custom profile using dynamic tuning
mkdir -p /etc/tuned/profiles/custom-profile
cat <<EOF >/etc/tuned/profiles/custom-profile/tuned.conf
[main]

[cpu]
load_threshold=0.5
latency_low=10
latency_high=10000
EOF

sed -i -r 's,^dynamic_tuning.*,dynamic_tuning = 1,' /etc/tuned/tuned-main.conf # changed in 2.22.0
systemctl restart tuned.service

# Set up the custom profile
tuned-adm profile custom-profile
tuned-adm active | grep custom-profile
check_arch
tuned-adm verify
sleep 60

# Check if the cpu latency is set to 10000
latency=$(get_cpu_latency)
if [ "${latency}" = "10000" ]; then
	echo "[I] CPU latency correctly set to 10000"
else
	echo "[E] CPU latency should be set to 10000"
	exit 1
fi

# Let's make the CPU busy
cat /dev/urandom > /dev/null &
PID=$!
sleep 60

# Check if the cpu latency is set to 10
latency=$(get_cpu_latency)
if [ "${latency}" = "10" ]; then
	echo "[I] CPU latency correctly set to 10"
else
	echo "[E] CPU latency should be set to 10"
	exit 1
fi

kill -9 ${PID}
sleep 60

# Check if the cpu latency is set to 10000
latency=$(get_cpu_latency)
if [ "${latency}" = "10000" ]; then
	echo "[I] CPU latency correctly set to 10000"
else
	echo "[E] CPU latency should be set to 10000"
	exit 1
fi
