#!/bin/bash
## kola:
##   tags: "platform-independent"
##   # The test is not available for aarch64 and s390x,
##   # as aarch64 is UEFI only and s390x is not using grub2
##   architectures: "! aarch64 s390x"
##   description: Verify that we install BIOS/PReP bootloader
##     using grub2-install from the target system.

# See
# - https://github.com/coreos/coreos-assembler/pull/3190
# - https://github.com/coreos/coreos-assembler/issues/3148

set -xeuo pipefail

# shellcheck disable=SC1091
. "$KOLA_EXT_DATA/commonlib.sh"

boot_dev=/boot
arch=$(arch)
grub_install_args=""
grub_modules=()
case ${arch} in
  x86_64)
    target=i386-pc
    core="${boot_dev}/grub2/${target}/core.img"
    partition=$(findmnt -no SOURCE ${boot_dev})
    device=$(lsblk --paths -no PKNAME ${partition})
    #
    # Handle modules for both the create_disk.sh case that only
    # includes "mdraid1x" and bootupd case (used when building using
    # OSBuild) that adds "part_gpt". The aleph stage in osbuild is
    # the only one that creates a file at /sysroot/.aleph-version.json
    #
    # https://github.com/coreos/fedora-coreos-tracker/issues/2187
    # We now also look for the aleph created by bootc as it
    # replaced the one created by osbuild since moving to
    # `bootc install` to create disk images.
    #
    # sync grub2-install parameters with the bootupd invocation from:
    # https://github.com/coreos/bootupd/blob/main/src/bios.rs
    grub_modules+=("mdraid1x")
    if [ -f /sysroot/.aleph-version.json ] || [ -f /sysroot/.bootc-aleph.json ]; then
        # collapse this if in't the previous line when all is moved
        # over to building using OSBuild.
        grub_modules+=("part_gpt")
    fi
    ;;

  ppc64le)
    target=powerpc-ieee1275
    core="${boot_dev}/grub2/${target}/core.elf"
    device=$(realpath /dev/disk/by-partlabel/PowerPC-PReP-boot)
    # sync grub2-install parameters with the bootupd invocation from:
    # https://github.com/coreos/bootupd/blob/main/src/bios.rs
    grub_install_args="--no-nvram"
    ;;

  *)
    fatal "grub2-install testing is not supported on ${arch}"
    ;;
esac

[ -e ${core} ] || fatal "file ${core} doesn't exist"
core_sum=$(sha256sum ${core} | awk '{print $1}')

mount -o remount,rw ${boot_dev}
grub2-install --target ${target} --boot-directory ${boot_dev} \
      ${grub_modules:+--modules "${grub_modules[*]}"}         \
      ${grub_install_args} ${device}

new_core_sum=$(sha256sum ${core} | awk '{print $1}')

# compare core.img checksum before and after run grub2-install
if [ "${core_sum}" != "${new_core_sum}" ]; then
  fatal "Error: not using grub2-install from target system"
fi
ok "using grub2-install from target system on ${arch}"
