# Bump the flatcar version stated here every time we or Red Hat change patches
# that modify parts of GRUB that are installed to the boot partition. Reset the
# version back to 1 when the upstream GRUB version changes.
FLATCAR_VERSION=flatcar3

# Gentoo's patches conflict with Red Hat's patches, and none of Gentoo's patches
# affect Flatcar, so skip them all.
PATCHES=()

# Adjust the version string for Flatcar. This propagates throughout the source.
cros_pre_src_prepare_adjust_version() {
	sed -i "/AC_INIT/s/\b${PV//./\\.}\b/\0-${FLATCAR_VERSION}/g" configure.ac || die
}

# Prevent developer test modules from being built. These are normally always
# installed, even by grub-install, but they have no use outside of testing and
# take up valuable space in /boot. The best way to identify these is to look for
# references to the tests/ directory.
cros_post_src_prepare_drop_tests() {
	gawk -i inplace '
		/^module = \{/ {
			in_mod = 1
		}
		in_mod {
			block = block $0 "\n"
		}
		/^\};/ && in_mod {
			if (block !~ /\<tests\//) {
				printf "%s", block
			}
			in_mod = 0
			block = ""
			next
		}
		!in_mod {
			print
		}
	' grub-core/Makefile.core.def || die
}

# Replace Gentoo's SBAT with Flatcar's.
cros_post_src_install_sbat() {
	insinto /usr/share/grub
	newins - sbat.csv <<-EOF
		sbat,1,SBAT Version,sbat,1,https://github.com/rhboot/shim/blob/main/SBAT.md
		grub,4,Free Software Foundation,grub,${PV},https://www.gnu.org/software/grub/
		grub.flatcar,1,Flatcar,grub2,${PV}-${FLATCAR_VERSION},https://github.com/flatcar/Flatcar
	EOF
}

# Flatcar does not use grub-install or grub-mkconfig. All the files under /etc
# relate to grub-mkconfig.
grub_install_mask=" ${EPREFIX}/etc/ *grub-install* *mkconfig* "
INSTALL_MASK+="${grub_install_mask}"
PKG_INSTALL_MASK+="${grub_install_mask}"
unset grub_install_mask
