#!/bin/bash
# vim: cindent:shiftwidth=4:tabstop=4:smarttab:textwidth=100

set -o posix
set -o errexit
set -o pipefail
set -o nounset
#set -o xtrace

#$title$ GNU GRand Unified Bootloader
#$check$ up-to-date modules are synchronized to /boot
#$ref$ /usr/lib/grub/i386-pc, /usr/lib/grub/x86_64-efi
#$author$ Rafal Rzeczkowski
#$version$ 0.6.1

level_check long

#CHANGELOG
#0.50	initial
#0.51	ensure that grub.cfg exists
#0.52	ignore Cobalt systems (uses native Linux bootloader)
#0.53	restyle according to https://kb.clearcable.ca/KB/ProgrammingStyleStandards
#0.54	downgrade failure report level to caution (wrong module version)
#0.55	integrate with the the FIX API
#0.6.0	support the UEFI version
#0.6.1	select OS version based on VERSION_ID not BCFG2_GROUPS membership

declare -r CFG='/boot/grub/grub.cfg'
if is_element_of hw-efi "${BCFG2_GROUPS[@]}"; then
	echodebug "GRand Unified Bootloader (EFI-AMD64 version)"
	declare -r SRC='/usr/lib/grub/x86_64-efi'
	declare -r DST='/boot/grub/x86_64-efi'
else
	echodebug "GRand Unified Bootloader (PC/BIOS version)"
	declare -r SRC='/usr/lib/grub/i386-pc'
	declare -r DST='/boot/grub/i386-pc'
fi

declare -r -a PROBLEMS=(PACKAGE_NOT_INSTALLED BOOT_NOT_MOUNTED CONFIGURATION_MISSING MODULE_VERSION_MISMATCH)
test -n ${#PROBLEMS[@]}

if [[ -d '/proc/cobalt' ]]; then
	unknown 'Cobalt RaQ platform does not use BIOS to boot'
	exit
fi

if [[ $VERSION_ID -le 6 ]]; then
	unknown 'unsupported obsolete OS version for domB/dom0'
	exit
fi

if [[ -d $SRC ]]; then
	echodebug "source files in $SRC"
else
	fail warning "source directory $SRC is missing"
	helpmsg 'GRUB package not installed correctly?'
	problem PACKAGE_NOT_INSTALLED $SRC
	exit
fi

if [[ -d "$DST" ]]; then
	echodebug "destination files in $DST"
else
	fail warning "destination directory $DST is missing"
	helpmsg 'verify that /boot is mounted'
	problem BOOT_NOT_MOUNTED NULL
	exit
fi

if [[ -s $CFG ]]; then
	echodebug "configuration file $CFG"
else
	fail critical "GRUB configuration file $CFG is missing --- system will not boot"
	helpmsg "use {update-grub} to regenerate $CFG"
	problem CONFIGURATION_MISSING $CFG
	exit
fi

cd $SRC
declare -i MOD_COUNT=0
for MOD in *.mod; do
	if cmp "$SRC/$MOD" "$DST/$MOD"; then
		MOD_COUNT=$((MOD_COUNT+1))
	else
		fail caution "installed module $MOD in $DST is different from the original copy in $SRC"
		helpmsg "reinstall GRUB into $DST"
		problem MODULE_VERSION_MISMATCH "$MOD"
		exit
	fi
done
echodebug "$MOD_COUNT dynamically loaded modules are synchronized"

ok
