#!/Users/cchildress/Documents/apply_cisco_config_hackathon/acc_virtenv/bin/python
# Copyright (C) 2010 Samuel Abels.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
import os
import sys
from optparse         import OptionParser
from Exscript         import __version__
from Exscriptd.Config import default_config_dir
from Exscriptd.config import modules

__dirname__ = os.path.dirname(__file__)

def get_usage(section = 'section', command = 'command'):
    return '%%prog [options] %s [options] %s [...]\n' % (section, command)

# Parse global options (all options before the first positional argument).
usage = get_usage() + 'Sections:'
for module_name, module in modules.iteritems():
    usage += '\n  ' + module_name.ljust(8) + '\t' + module.get_description()

parser = OptionParser(usage = usage, version = __version__)
parser.disable_interspersed_args()
parser.add_option('--config-dir',
                  dest    = 'config_dir',
                  default = default_config_dir,
                  metavar = 'FILE',
                  help    = '''
The XML config file for the Exscript daemon.
'''.strip())

global_options, args = parser.parse_args()

# Parse section-specific options (all options before the second positional
# argument).
try:
    section = args.pop(0)
except IndexError:
    parser.error('section argument missing')

try:
    module = modules[section]
except KeyError:
    parser.error('no such section: %s' % section)

def which(program):
    def is_exe(fpath):
        return os.path.exists(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file
    return None

exscript_binary = which('exscriptd')
if exscript_binary is None:
    path = repr(os.environ.get('PATH'))
    parser.error('exscriptd executable not found. PATH was ' + path)
print 'exscriptd found at ' + exscript_binary
script_dir = os.path.dirname(exscript_binary)

handler = module(global_options, script_dir = script_dir)
usage   = get_usage(section) + 'Commands:'
for command_name, command in handler.get_commands():
    usage += '\n  ' + command_name.ljust(8) + '\t' + command

parser = OptionParser(usage = usage)
parser.disable_interspersed_args()
section_options, args = parser.parse_args(args)

# Parse command-specific options (all remaining options).
try:
    command = args.pop(0)
except IndexError:
    parser.error('command argument missing')

# Get the command handler.
try:
    start = getattr(handler, 'start_' + command)
except AttributeError:
    parser.error('no such command: %s' % command)

usage  = get_usage(section, command)
parser = OptionParser(usage = usage)
try:
    optadd = getattr(handler, 'getopt_' + command)
except AttributeError:
    pass
else:
    optadd(parser)
handler.options, args = parser.parse_args(args)

# Check the command specific arguments.
try:
    prepare = getattr(handler, 'prepare_' + command)
except AttributeError:
    pass
else:
    try:
        prepare(parser, *args)
    except TypeError:
        parser.error('invalid number of arguments for this command')

start()
