#!/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. The format of the
# mapping file is that each line starts with the text of the menu item,
# then a comma, and then the name of the menu program to run for that menu
# item.

. /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 -or -type l \) -perm -700 -printf '%f\n'); do
			if [ -e menu/$i.mnu ]; then
				if [ "$NEW" ] || grep -q '^Only-New: false' menu/$i.mnu; then
					echo $(grep ^Order: menu/$i.mnu | cut -f 2 -d ' ') $i
				fi
			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"
		RET=$(echo "$RET" | sed 's/,//g')
		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"
