#!/usr/bin/bash

if [ -z "$TMT_TEST_PIDFILE" ]; then
    echo "tmt-reboot can be used only in the context of a running test."
    exit 1
fi

# Two-level reboot: `tmt-reboot` extracts command line arguments, and
# calls `tmt-reboot-core` *while holding the tmt test pidfile lock!*
# That should assure the pidfile would exist and contain valid info.

[ -n "$TMT_DEBUG" ] && set -x

TMT_TEST_PIDFILE_LOCK="${TMT_TEST_PIDFILE_LOCK:-/var/tmp/tmt-test.pid}"

PATH=/sbin:/usr/sbin:$PATH

command=""
timeout=""

while getopts "c:t:e" flag; do
    case "${flag}" in
        c) command="${OPTARG}";;
        t) timeout="${OPTARG}";;
        e) logger -s "The '-e' option is noop as of tmt-1.58, see release docs for more information.";;
        *) exit 1;;
    esac
done

# Handle EFI for Beaker
if [[ -f /root/EFI_BOOT_ENTRY.TXT ]]; then
    if efibootmgr &>/dev/null ; then
        os_boot_entry=$(efibootmgr | grep 'BootCurrent' | cut -d' ' -f2)
        # fall back to /root/EFI_BOOT_ENTRY.TXT if BootCurrent is not available
        if [[ -z "$os_boot_entry" ]] ; then
            logger -s "No 'BootCurrent' found, falling back to '/root/EFI_BOOT_ENTRY.TXT'."
            os_boot_entry=$(</root/EFI_BOOT_ENTRY.TXT)
        fi
        if [[ -n "$os_boot_entry" ]] ; then
            logger -s "efibootmgr -n $os_boot_entry"
            efibootmgr -n "$os_boot_entry"
        else
            logger -s "Could not determine the value for 'BootNext', no changes were made."
        fi
    else
        logger -s "No 'efibootmgr' command found, skipping handling of EFI for Beaker."
    fi
fi

flock "$TMT_TEST_PIDFILE_LOCK" tmt-reboot-core "$command" "$timeout"
