#!/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=""
systemd_soft_reboot=""

while getopts "c:t:esh" 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.";;
        s) systemd_soft_reboot="true";;
        h) echo "Usage: tmt-reboot [-c COMMAND] [-t TIMEOUT] [-s] [-h]"
           echo "  -c COMMAND  Custom reboot command to use"
           echo "  -t TIMEOUT  Timeout in seconds"
           echo "  -s          Use systemd soft-reboot (preserves kernel state)"
           echo "  -h          Show this help message"
           exit 0;;
        *) echo "Usage: tmt-reboot [-c COMMAND] [-t TIMEOUT] [-s] [-h]"
           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" "$systemd_soft_reboot"
