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

# snippets are not going into the actual image
final_exit () {
	if [ "$DEBUG" != 2 ]; then rm -r .in/; fi
	exit 0
}

MODDIR="/usr/lib/syslinux"

case "$GLOBAL_BOOTLOADER" in
	isolinux|syslinux) CFG="$GLOBAL_BOOTLOADER.cfg";;
	*) CFG="isolinux.cfg";;
esac

cd "$WORKDIR/syslinux"

# number ordering sponsored by shell's pathname expansion
grep -hv '^#' .in/[0-9][0-9]*.cfg > "$CFG"

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

# validate just in case (see also stage1 Makefile)
case "$GLOBAL_BOOTLOADER" in
	isolinux|syslinux) ;;
	*) final_exit;;
esac

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

# prune module-specific config snippets; skip built-in one
SYSLINUX_MODULES="$(cat .in/modules.list)"
if [ -n "$SYSLINUX_MODULES" ]; then
	for module in $SYSLINUX_MODULES; do
		if [ "$modules" == "prompt" ]; then continue; fi
		cp -a $MODDIR/$module.c?? . || rm .in/[0-9][0-9]$module.cfg
	done
fi

final_exit

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