#!/bin/sh

set -e

# amd file path
if [ $(uname -m) = "x86_64" ]; then
    bootx=/usr/lib/grub/efi-backup/bootx64.efi
    grubx=/usr/lib/grub/efi-backup/grubx64.efi
    shimx=/usr/lib/grub/efi-backup/shimx64.efi
fi
#arm file path
if [ $(uname -m) = "aarch64" ]; then
    bootx=/usr/lib/grub/efi-backup/bootaa64.efi
    grubx=/usr/lib/grub/efi-backup/grubaa64.efi
    shimx=/usr/lib/grub/efi-backup/shimaa64.efi
fi

copy_file() {
    for file in $(ls $1)
    do
        if [ -d $1"/"${file} ]; then
            [ ${file} = "boot" ] && [ -s ${bootx} ] && cp -a ${bootx} $1"/"${file}/
            [ -s ${grubx} ] && cp -a ${grubx} $1"/"${file}/
            [ -s ${shimx} ] && cp -a ${shimx} $1"/"${file}/
        fi
    done
}

efiDev=$1
boot_loader_type=$2
boot_pkname_device=$3

if [ "legacy" = "$boot_loader_type" ]; then
    if [ ! -d /boot ]; then
        mkdir /boot
    fi
    mount $efiDev /boot
    grub-install --no-floppy $boot_pkname_device --target=i386-pc --force 2>/dev/null
    umount $efiDev
    exit 0
fi

[ -z ${efiDev} ] && exit -1

mount ${efiDev} /mnt

copy_file /mnt/EFI/

umount /mnt
exit 0