#!/bin/bash

set -e -x

remove_boot_entry ()
{
    local efi_distributor="$*"

    efi_entries=`efibootmgr | grep '^Boot[0-9]' | fgrep -i " $efi_distributor" | fgrep -v "Rescue" | cut -b5-8`

    for bootentry in ${efi_entries}; do
        efibootmgr -q -b "$bootentry" -B
    done
}

add_boot_entry ()
{
    local device_node="$1"
    shift
    local partition_number="$1"
    shift
    local efi_loader="$1"
    shift
    local efi_distributor="$*"

    # Delete old entries from the same distributor.
    remove_boot_entry $efi_distributor

    efibootmgr -c -d $device_node -p $partition_number -l "$efi_loader" -L "$efi_distributor"
}

clean_boot_entry ()
{
    for bootnum in `efibootmgr | grep '^Boot000[0-9]' | cut -b5-8`; do
        efibootmgr -q -b "$bootnum" -B
    done
}

check_boot_entry ()
{
    local efi_loader="$1"
    shift
    local efi_distributor="$*"
    for bootnum in `efibootmgr | grep '^Boot[0-9]' | fgrep -i " $efi_distributor" | cut -b5-8`; do
        if [ "$(efibootmgr -v | grep Boot$bootnum | grep -Po 'File\(.*\)')" = "File($efi_loader)" ]; then
            exit 0
        fi
        efibootmgr -q -b "$bootnum" -B
    done
    exit 1
}

case $1 in
    (add)
        shift
        add_boot_entry $*
        ;;
    (remove)
        shift
        remove_boot_entry $*
        ;;
    (check)
        shift
        check_boot_entry $*
        ;;
    (clean)
        shift
        clean_boot_entry $*
        ;;
esac
