#!/bin/sh -e
# This helper program is run by base-config before displaying the main
# menu. It populates the base-config/main-menu's choices list with the menu
# choices, and generates a menu-mapping file that can be used to translate
# back from the menu items to the programs to run.

. /usr/share/debconf/confmodule

SET_DEFAULT=$1

# Get an ordered list of the menu items.
get_menu_items () {
	(
		for i in $(find menu -type f -perm -700 -printf '%f\n' | grep -v .tst); do
			if [ "$NEW" ] || grep -q '^Only-New: false' menu/$i.mnu; then
				echo $(grep ^Order: menu/$i.mnu | cut -f 2 -d ' ') $i
			fi
		done
	) | sort -n | cut -d ' ' -f 2
}

rm -f menu-mapping
CHOICES=""
for item in $(get_menu_items); do
	testscript=menu/$(echo $item | sed 's/.mnu$//').tst
	if ! [ -x $testscript ] || $testscript; then
		db_metaget base-config/menu/$item description || RET="$item"
		echo "$RET:$item" >> menu-mapping
		if [ -z "$CHOICES" ]; then
			CHOICES="$RET"
			if [ "$SET_DEFAULT" -eq 1 ]; then
			    # Mark first menu item as default to get things
			    # going.
			    db_set base-config/main-menu "$RET"
			fi
		else
			CHOICES="$CHOICES, $RET"
		fi
	fi
done

db_subst base-config/main-menu CHOICES "$CHOICES"
