#! /bin/sh
set -e

# grub-mkconfig helper script.
# Copyright (C) 2006,2007,2008,2009,2010  Free Software Foundation, Inc.
#
# GRUB is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GRUB is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GRUB.  If not, see <http://www.gnu.org/licenses/>.

################################################################################
#
# Copyright (C) 2014,2015,2016 Cumulus Networks Inc. All rights reserved
#
# Modified to add ONIE compatible Diagnostic partition
#
################################################################################

# Look for an ONIE compatible DIAG image and add a boot entry for it.
# Depends on UEFI GRUB or Legacy BIOS GRUB
uefi_root=/boot/efi
onie_uefi_grub=EFI/onie/grubx64.efi
diag_label=$(blkid | grep -- '-DIAG"' | sed -e 's/^.*LABEL="//' -e 's/".*$//')
if [ -n "$diag_label" ]  ; then
    if [ -d "/sys/firmware/efi/efivars" ] && [ -f "${uefi_root}/$onie_uefi_grub" ] ; then
        # UEFI firmware
        diag_uefi_grub=$(efibootmgr -v | grep $diag_label | sed -e 's/.*)\/File(//' -e 's/)//' -e 's/\\/\//g')
        if [ -f "$uefi_root/$diag_uefi_grub" ] ; then
            cat <<EOF
menuentry '$diag_label' {
	set root='(hd0,gpt1)'
	search --no-floppy --fs-uuid --set=root $uefi_uuid
        echo    'Loading $diag_label $onie_platform ...'
	chainloader /$diag_uefi_grub
}
EOF
        fi
    else
        # legacy BIOS firmware
        cat <<EOF
menuentry '$diag_label' {
        search --no-floppy --label --set=root $diag_label
        echo    'Loading $diag_label $onie_platform ...'
        chainloader +1
}
EOF
    fi
fi
