#!/bin/bash
## kola:
##   exclusive: false
##   description: Verify that bootupd works.

# We generally implement project-owned tests run in the pipeline
# and be able to run the existing bootupd tests.
# See https://github.com/coreos/fedora-coreos-config/pull/677

set -xeuo pipefail

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

# Not all streams on which this test runs has bootupd on all arches yet. On
# x86_64 and aarch64, we always expect bootupd to be installed. On ppc64le and
# s390x, let's just conditionally check that *if* bootupd is installed, then
# it's functioning as expected. We can harden it more once we've hard cut over
# to 9.4.

current_arch="$(arch)"

check_bootloader_service_inactive() {
    local bl_active
    bl_active=$(systemctl is-active bootloader-update.service 2>&1 || true)
    if [ "${bl_active}" != "inactive" ]; then
        fatal "bootloader-update.service is ${bl_active} on ${current_arch}"
    fi
}

check_grub_version() {
    local package="$1"
    local format="$2"
    local version
    version=$(rpm -q "$package" --qf "$format")
    if [ -z "$version" ]; then
        fatal "Could not retrieve version for package ${package}"
    fi
    if ! bootupctl status | grep -F "${version}"; then
        fatal "bootupctl status output should include ${package} package version"
    fi
}

check_state_file=

case "$current_arch" in
    aarch64|x86_64)
        # on these arches, we always expect state files to exist
        check_state_file=1
        # aarch64 (and x86_64) uses uefi firmware, should check grub2
        check_grub_version "grub2-common" '%{EVR}'
        ;;
    ppc64le|s390x)
        # For ppc64le and s390x, only check if bootupd is installed
        if ! rpm -q bootupd &>/dev/null; then
            exit 0
        fi

        check_bootloader_service_inactive

        # ppc64le-specific checks
        if [ "$current_arch" = "ppc64le" ]; then
            # ppc64le has it if built by osbuild, otherwise not
            if [ -e /sysroot/.aleph-version.json ]; then
                check_state_file=1
            fi
            # ppc64le (and x86_64) uses bios firmware, should check grub2-tools
            check_grub_version "grub2-tools" '%{NEVRA}'
        fi
        ;;
    *) fatal "Unhandled architecture: ${current_arch}" ;;
esac

state_file=/boot/bootupd-state.json
if [ -n "${check_state_file}" ] && [ ! -f "${state_file}" ]; then
    fatal "${state_file} not present"
fi

# Verify `bootupctl status` output contains related content.
# https://github.com/coreos/bootupd/issues/694
if ! bootupctl status | grep "CoreOS aleph version"; then
    fatal "bootupctl status output should include 'CoreOS aleph version'"
fi

ok bootupctl
