#!/bin/bash

set -e

cleanup() {
    rc=$?
    set +e
    if [ ${rc} -ne 0 ]; then
        echo "## Something failed"
        echo
        echo "## tuned journal logs"
        journalctl -u tuned.service --lines 100
        echo
        echo "## tuned.log"
        tail -n100 /var/log/tuned/tuned.log
        echo
        echo "## backing_file=${backing_file}"
        ls -la "${backing_file}"
        echo
        echo "## losetup"
        losetup -a
        echo
    fi
    echo "Cleaning up"
    losetup -d "${loopdev}" || :
    rm -f "${backing_file}"
}

backing_file=$(mktemp)

trap cleanup EXIT

echo "## Creating loop device"
truncate -s 100M "${backing_file}"
loopdev=$(losetup --show -f "${backing_file}")
echo
echo "## We have ${loopdev}"
test -b "${loopdev}"
ls -la "${loopdev}"
losetup -l "${loopdev}"

echo
echo "## Setting profile to automatic"
tuned-adm auto_profile

echo
echo "## Selected profile"
tuned-adm active

echo
echo "## Restarting tuned"
systemctl restart tuned
echo
echo "## Checking that ${loopdev} is NOT in the list of devices assigned to the disk plugin"
devices=$(tuned-adm instance_get_devices disk)
echo "## list of devices the disk plugin cares about:"
echo "${devices}"
if echo "${devices}" | grep -qE "^$(basename ${loopdev})"; then
    echo "## FAIL, device ${loopdev} is in the list"
    exit 1
else
    echo "## OK, device ${loopdev} is NOT in the list"
fi

