#!/bin/bash

. /usr/local/Reductor/etc/const
. $CONFIG

export default="mainmenu"
export tmpfile=/tmp/menu.$$
export cmd=''
export global_index=''
export GLOBAL_PARAMS=( "$@" )
export DEF_COUNT=5
REGNUM="$($BINDIR/reg_util create)"
baseopts="--stdout --output-fd 2 --colors --trim  --backtitle '${app[name]}: $(get_reductor_state)' --cancel-label 'Назад' --ok-label 'Выбрать' --no-shadow --item-help"
export REGNUM
export baseopts

#avoid putty bugs
[ "$TERM" = xterm ] && TERM=linux

_LOGFILE="$LOGDIR/$(basename $0).log"

check_dialog() {
	if [ -z "$(which dialog 2>>"$_LOGFILE")" ]; then
		if [ -n "$(which yum 2>>"$_LOGFILE")" ]; then
			echo "No 'dialog' found, try to: yum install dialog"
			yum -y install dialog
		fi
	fi
}

declare -A main
shopt -s extglob
mkdir -p $USERDIR/backups/

. $MENULIB


check_dialog
touch /var/log/menu.log &>>"$_LOGFILE"
cd ${MAINDIR}



create_mainmenu() {
	declare -A item
	while read _ _ array_name; do
		eval item="$(set | grep "^$array_name=" | sed s/$array_name=//)"
		[ -z "${item['widget']}" ] && continue
		main[$array_name]=""
		main[$array_name.widget]="${item['widget']}"
	done <<< "$(fgrep declare $CONFIG)"
	main[widget]="menu 'Меню ${app['name']}'"
	return 0
}

update_instcode() {
	if [ -f ${PROCLIST} ]; then
		reg['installcode']=$(get_reductor_instcode)
		save_and_exit
	fi
}

main() {
	update_instcode
	create_mainmenu
	show_recur main mainmenu
	if dialog --yesno "Сохранить изменения?" 5 30; then
		save_and_exit
	fi
	clear
}

${1:-main}
