#!/bin/bash
set -euo pipefail
shopt -s inherit_errexit

# shellcheck source=scripts/libcc
. /usr/lib/common-criteria/scripts/libcc

SHIM="shim-sles.efi"
SHIM_CFG="/etc/default/shim"

check_70_config_shim() {
	if [ ! -f "$SHIM_CFG" ]; then
		echo "$SHIM_CFG missing"
		return 1
	fi
	if ! grep -q "^def_shim_efi=$SHIM$" "$SHIM_CFG"; then
		echo "$SHIM_CFG not set to def_shim_efi=$SHIM"
		return 1
	fi
}

apply_70_config_shim() {
	if check_70_config_shim; then
		cc_echo "$SHIM_CFG already configured for $SHIM"
		return 0
	fi

	cc_echo "configuring use of $SHIM"
	echo "def_shim_efi=$SHIM" > "$SHIM_CFG.new"
	if [ -e "$SHIM_CFG" ]; then
		cc_replace "$SHIM_CFG.new" "$SHIM_CFG"
	else
		mv "$SHIM_CFG.new" "$SHIM_CFG"
	fi
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
	cc_start_logging
	trap 'cc_exit $?' ERR
	apply_70_config_shim
	cc_exit 0
fi
