#!/bin/bash
ID=rosa
GRUBDIR=/boot/grub2
MNTPOINT=/boot/efi

# continue if EFI
[ -d /sys/firmware/efi ] || exit 0

# continue if x86_64 or x86
ARCH=$(arch)
echo $ARCH |grep -q "86" || exit 0

# continue only if bootloaders installed by Rosa
[ "$(find /boot -name 'rosa-iso-build*')" ] || exit 0

# If live OS no need to install bootloader
# anaconda install grub earlier
if losetup |grep -q 'LiveOS/rootfs.img' ; then
    echo "Rosa live detected, skip grub2-install; update-grub2"
else
    [ "$(find /boot -name 'shim*')" ] || dnf reinstall -y shim-unsigned || exit ${LINENO}
    grub2-install $(df -h /boot | (read; awk '{print $1; exit}'|sed 's/[[:digit:]]*$//'))
    update-grub2
fi

# continue if grub
[ -d "$GRUBDIR" ]   || exit ${LINENO}

pushd $MNTPOINT
EFIDIR="$(ls -1d {EFI,efi,Efi} |tail -n1)"
[ "$EFIDIR" ] || EFIDIR=EFI

pushd ${EFIDIR}
df -t vfat ./ 2>/dev/null 1>&2 || exit ${LINENO}
[ -d "$ID" ] || exit ${LINENO}

BOOTDIR=$(ls -1d {BOOT,boot,Boot} |tail -n1)
[ "$BOOTDIR" ] || BOOTDIR='BOOT'
mkdir -p $BOOTDIR

# continue if /EFI/BOOT is empty, or if rosa bootloaders in /EFI/BOOT
[ "$(ls -1 $BOOTDIR)" ] && [ ! -f "$BOOTDIR/${ID}.readme" ] && exit ${LINENO}

PREFIX=x64
[ "$ARCH" != 'x86_64' ] && PRREFIX=ia32

rm -f ${BOOTDIR}/*
cp -f ${ID}/* ${BOOTDIR}/
mv ${BOOTDIR}/shim* ${BOOTDIR}/BOOT${PREFIX}.efi
cat << EOF > "${BOOTDIR}/${ID}.readme"
Rosa efi boot hook. Do not remove this file
files in ${EFIDIR}/BOOT/  were copied from the ${EFIDIR}/rosa/
EOF
popd
popd
