#!/bin/sh

#
# Copyright (C) 2017 Cumulus Networks Inc.
# All rights reserved
#
# Wrapper around efibootmgr for setting up UEFI BootNext variable
#

set -e

[ -d /sys/firmware/efi ] || {
    echo "ERROR: EFI variables are not supported on this system"
    exit 1
}

efibm="/bin/efibootmgr"

[ -x "$efibm" ] || {
    echo "ERROR: Unable to find efibootmgr utility: $efibm"
    exit 1
}

# Given a boot label in $1, return the corresponding EFI boot variable
# number.
get_efi_boot_num() {
    local num=$("$efibm" | grep "$1" | head -n 1 | awk '{ print $1 }')
    # Strip leading "Boot"
    num=${num#Boot}
    # String trailing "*"
    num=${num%\*}
    echo -n $num
}

#
# For UEFI, set system to boot the specified label.  It is an error if
# the label cannot be found.
#

label="$1"
boot_num=$(get_efi_boot_num "$label")

[ -n "$boot_num" ] || {
    echo "ERROR: Unable to detemine UEFI boot number for label: $label"
    exit 1
}

# Set the UEFI BootNext variable to the boot number.  This is a one time boot.
$efibm -q -n $boot_num || {
    echo "ERROR: Unable to set UEFI BootNext to $boot_num for label: $label"
    exit 1
}
