#!/usr/bin/python
#
# $Id$
#
#
# generic menu program.. reads in the sections, and runs a shell program
# for each section, or calls a submenu.
#
#
#  Version 0.1 Copyright Duncan Robertson duncan@linuxbandwagon.com
#  July 2001
#
#  This program is released under the Gnu General Public License
#  see http://www.gnu.org/licenses/gpl.html for further information.
#
#
cvsid = 'Id$'

# default menu.ini, can specify another.
configini = '/usr/local/etc/menu.ini'

from snack import *
import sys, ConfigParser, commands, os, time, glob, pty

def run_menu(configs,screen):

   screen.pushHelpLine('<TAB> or arrow keys to move between elements, <Enter> to select')
   screen.drawRootText(0,1,configs.get('DEFAULT','root'))
   screen.drawRootText(0,0,sys.argv[0]+' '+cvsid)
   exitchosen = 0

   menulist = []
   sections = configs.sections()

   for section in sections:
      if 'label' in configs.options(section):
         menulist.append(configs.get(section,'label'))
      else:
         menulist.append(section)

   while not exitchosen:
      mresult = ListboxChoiceWindow(screen,
         configs.get('DEFAULT','title'),
         configs.get('DEFAULT','text'),
         menulist,
         ('ok', 'exit'),
         60,1,12)

      menuchosen = sections[mresult[1]]
      exitchosen = int(configs.get(menuchosen,'exit'))
      if mresult[0] == 'exit':
         exitchosen = 1
      if exitchosen:
         # may as well bail here
         continue

      if 'prompt' in configs.options(menuchosen)\
         and (configs.get(menuchosen,'prompt') == 'yes'):
         #
         # do a do you want to proceed type thing here
         #
         dchoice = ButtonChoiceWindow(screen,
            'Are you sure?',
            menulist[mresult[1]],
            ['yes','no']) 
         if dchoice == 'no':
            # bail, loop again
            continue

      if 'command' in configs.options(menuchosen):
         screen.finish()
         command = configs.get(menuchosen,'command')
         os.system(command)
         if 'aftercommand' in configs.options(menuchosen):
            aftercommand = configs.get(menuchosen,'aftercommand')
            os.system(aftercommand)
         screen = SnackScreen()
         screen.pushHelpLine('<TAB> or arrow keys to move between elements, <Enter> to select')
         screen.drawRootText(0,1,configs.get('DEFAULT','root'))
         screen.drawRootText(0,0,sys.argv[0]+' '+cvsid)
      if 'menu' in configs.options(menuchosen):
         submenuini = configs.get(menuchosen,'menu')
         subconf = ConfigParser.ConfigParser()
         subconf.read(submenuini)
         run_menu(subconf,screen)

#
# main() bit
#

if len(sys.argv) == 2:
   configini = sys.argv[1]

configs = ConfigParser.ConfigParser()
configs.read(configini)

screen = SnackScreen()

run_menu(configs,screen)


screen.finish()
