#!/bin/sh
# gather grub configuration from snippets;
# copy modules; see also this feature's generate.mk

CFG="$WORKDIR/boot/grub/grub.cfg"
CFG_EFI="$WORKDIR/EFI/BOOT/grub.cfg"

if [ -n "$GLOBAL_EFI_BOOTLOADER" -a ! "$GLOBAL_EFI_BOOTLOADER" = "grub-efi" ]; then
	rm -fr "$WORKDIR/boot"
	exit 0
fi

if [ -z "$GLOBAL_EFI_BOOTLOADER" ]; then
	case "$GLOBAL_BOOTLOADER" in
		ieee1275boot) ;;
		*) rm -fr "$WORKDIR/boot"
		   exit 0;;
	esac
fi

cd "$WORKDIR/boot/grub"

# copy extra files, if any
GRUB_FILES="$(cat .in/grub.list)"
if [ -n "${GRUB_FILES% }" ]; then
	cp -a $GRUB_FILES .
fi

# number ordering sponsored by shell's pathname expansion
case "$GLOBAL_BOOTLOADER" in
	ieee1275boot)
		grep -hv '^#' $(find .in/*.cfg -not -name *_efi.cfg) > "$CFG" ;;
esac

if [ "$GLOBAL_EFI_BOOTLOADER" = "grub-efi" ]; then
	mkdir -p "$WORKDIR/EFI/BOOT"
	grep -hv '^#' $(find .in/*.cfg) > "$CFG_EFI"
fi

# there should be DEFAULT directive there (at least for alterator-netinst)
default_change() {
local CFG=$1
if [ -n "$GLOBAL_GRUB_DEFAULT" ]; then
	if [ -n "$(grep -i "$GLOBAL_GRUB_DEFAULT" "$CFG")" ]; then
		DEFAULT="$GLOBAL_GRUB_DEFAULT"
		sed -i '/^default/d'
		echo "default=$DEFAULT" >> "$CFG"
	else
		echo "error: $GLOBAL_GRUB_DEFAULT missing in $CFG" >&2
		exit 1
	fi
fi
if ! grep -i '^default' "$CFG"; then
	DEFAULT="$(grep -i '\-\-id ' "$CFG" | head -1 | rev| cut -f2 -d' ' |rev)"
	if [ -n "$DEFAULT" ]; then
		echo "default=$DEFAULT" >> "$CFG"
	else
		echo "error: no DEFAULT or UI directive and cannot guess for $CFG" >&2
		exit 1
	fi
fi
}

if [ -f "$CFG" ]; then
	default_change "$CFG"
	sed -i 's,@boot_path@,/boot,g' "$CFG"
fi

if [ -f "$CFG_EFI" ]; then
	default_change "$CFG_EFI"
	sed -i 's,@boot_path@,/EFI/BOOT,g' "$CFG_EFI"
fi

# change @linux_suffix@
case "$GLOBAL_ARCH" in
	i586|x86_64)
		[ ! -f "$CFG" ] || sed -i 's/@linux_suffix@/16/g' "$CFG"
		[ ! -f "$CFG_EFI" ] || sed -i 's/@linux_suffix@/efi/g' "$CFG_EFI"
	;;
	*)
		[ ! -f "$CFG" ] || sed -i 's/@linux_suffix@//g' "$CFG"
		[ ! -f "$CFG_EFI" ] || sed -i 's/@linux_suffix@//g' "$CFG_EFI"
	;;
esac

# snippets are not going into the actual image
if [ "$DEBUG" != 2 ]; then
	rm -r .in/
	cd $WORKDIR
	[ -f "$CFG" ] || rm -r boot/grub
	[ ! $(ls -A boot/ | wc -l) -eq 0 ] || rm -r boot/
fi

# NB: there will be final macro expansion based on actual image sizes
#     done by features.in/grub/scripts.d/20-propagator-ramdisk
