#!/bin/sh

################################################################################
#
# Copyright (C) 2015 Cumulus Networks Inc. All rights reserved
#
################################################################################

# Use the 50_onie_grub fragment from the ONIE installation

[ -r /usr/lib/cumulus/onie/onie-tools-common ] || exit 0

. /usr/lib/cumulus/onie/onie-tools-common

cl_mount_onie_tools ro || {
    echo "Mounting ONIE tools failed" >&2
    exit 1
}

# Sanitize the $GRUB_CMDLINE_LINUX_DEFAULT and $GRUB_CMDLINE_LINUX
# variables that are passed to ONIE's grub generator.  At the end
# collapse the content of the two variables into $GRUB_CMDLINE_LINUX.

tmp_cmdline=
for a in $GRUB_CMDLINE_LINUX_DEFAULT $GRUB_CMDLINE_LINUX ; do
    case "$a" in
        quiet)
            # Remove 'quiet' as ONIE adds that automatically.
            continue
            ;;
        cl_*)
            # Remove any Cumulus variables
            continue
            ;;
        *)
            # Preserve the rest
            tmp_cmdline="${tmp_cmdline} $a"
    esac
done
GRUB_CMDLINE_LINUX_DEFAULT=""
GRUB_CMDLINE_LINUX="$tmp_cmdline"

onie_grub_tmp=no
if [ -x "$onie_grub_d_dir/50_onie_grub" ] ; then
    # Use the 50_onie_grub grub.d fragment that comes from the ONIE
    # distribution.
    onie_grub_tmp=$(mktemp /tmp/onie-grub.XXXX)
    cp $onie_grub_d_dir/50_onie_grub $onie_grub_tmp
    chmod +x $onie_grub_tmp
fi

# Un-mount the onie-tools directory as the 50_onie_grub fragment (if
# found) also wants to mount the onie-tools.
cl_umount_onie_tools

if [ -d /sys/firmware/efi ] ; then
    # The ONIE grub fragment needs this variable set for UEFI
    export onie_grub_image_name=grubx64.efi
fi

if [ "$onie_grub_tmp" != "no" ] ; then
    $onie_grub_tmp
    rm -f $onie_grub_tmp
else
    # use a fallback copy that might be out of date, but better than
    # nothing.
    echo "Warning: 50_onie_grub is unavailable.  Using cached copy." >&2
    /usr/lib/cumulus/onie/50_onie_grub_fallback "$@"
fi
