#!/usr/bin/python
 
import os
import sys
import ConfigParser
import re
from optparse import OptionParser
 
syntax = ""
parser = OptionParser(usage=syntax)
parser.add_option("-c", "--config",dest = "config",action = "store",help = "Configuration you want to use to power the menu")
(options, args) = parser.parse_args()
 
menuoptions = list()
 
if not options.config:
    print "Unable to continue with out a config"
    parser.print_help()
else:
    try:
        config = ConfigParser.ConfigParser()
        try:
            config.read(options.config)
        except:
            print "Error - unable to load config file"
            sys.exit()
        ok = 1
 
        while ok == 1:
            count = 0
            print
            print config.get('main','title') + " - " + config.get('main','desc')
            print
            for section in sorted(config.sections()):
                if not re.match('main',section):
                    print "\t" + str(count) + ") " + config.get(section,'name') + " - " + config.get(section,'desc')
                    menuoptions.append(section)
                    count += 1
            print "\tx) exit - exit "
            print "?: ",
            choice = sys.stdin.readline()
            print
            if re.match('^x|X$',choice):
                print "eXiting ..."
                ok = 0
            else:
                if re.match('^\d+$',choice):
                    choice = int(choice)
                    try:
                        if menuoptions[choice]:
                            cmd_var_count = 1
                            cmd = config.get(menuoptions[choice],'cmd')
                            while config.has_option(menuoptions[choice],"cmd-var" + str(cmd_var_count)):
                                var = str("cmd-var" + str(cmd_var_count)).upper()
                                print config.get(menuoptions[choice],"cmd-var" + str(cmd_var_count))
                                print "?: ",
                                cmd = str(cmd).replace(var,sys.stdin.readline())
                                cmd_var_count += 1
                            print
                            print "Command to be executed: " + cmd
                            print
                            print "Output:"
                            os.system(cmd)
                            print 
                    except IndexError:
                        print "Error - Sorry that is not a choice"
                        print
                        ok = 1
                else:
                    print "Error - Sorry that is not a choice"
                    print 
                    ok = 1
    except KeyboardInterrupt:
        print
        print "exiting ...."
sys.exit()