#!/usr/bin/python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
#   See COPYING file distributed along with the testkraut package for the
#   copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
""""""

__docformat__ = 'restructuredtext'

import logging
# set up logging
logging.basicConfig(
        format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
    )
log_levels = dict(critical=logging.CRITICAL, error=logging.ERROR,
                  warning=logging.WARNING, info=logging.INFO,
                  debug=logging.DEBUG)
lgr = logging.getLogger()

import sys
import argparse
import textwrap
import testkraut.cmdline as mvcmd
from testkraut.cmdline import helpers, common_args
import testkraut

def _license_info():
    return """\
Copyright (c) 2012 testkraut developers

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Written by Michael Hanke with the help of numerous other contributors.
"""


# setup cmdline args parser
# main parser
parser = argparse.ArgumentParser(
                fromfile_prefix_chars='@',
                # usage="%(prog)s ...",
                description="""\
Here is an initial description that clearly needs improvement.
Anyway, here are the currently available commands:
""",
                epilog='',
                formatter_class=argparse.RawDescriptionHelpFormatter,
                add_help=False
            )
# common options
helpers.parser_add_common_opt(parser, 'help')
helpers.parser_add_common_opt(parser,
                              'version',
                              version='testkraut %s\n\n%s' % (testkraut.__version__,
                                                          _license_info()))
if __debug__:
    parser.add_argument(
        '--dbg', action='store_true', dest='common_debug',
        help="do not catch exceptions and show exception traceback")
parser.add_argument('--log-level',
                    choices=('critical', 'error', 'warning', 'info', 'debug'),
                    dest='common_log_level',
                    help='log level')


# subparsers
subparsers = parser.add_subparsers()
# for all subcommand modules it can find
cmd_short_description = []
for cmd in sorted([c for c in dir(mvcmd) if c.startswith('cmd_')]):
    cmd_name = cmd[4:]
    subcmdmod = getattr(__import__('testkraut.cmdline',
                                   globals(), locals(),
                                   [cmd], -1),
                        cmd)
    # deal with optional parser args
    if 'parser_args' in subcmdmod.__dict__:
        parser_args = subcmdmod.parser_args
    else:
        parser_args = dict()
    # use module description, if no explicit description is available
    if not 'description' in parser_args:
        parser_args['description'] = subcmdmod.__doc__
    # create subparser, use module suffix as cmd name
    subparser = subparsers.add_parser(cmd_name, add_help=False, **parser_args)
    # all subparser can report the version
    helpers.parser_add_common_opt(
            subparser, 'version',
            version='testkraut-%s %s\n\n%s' % (cmd_name, testkraut.__version__,
                                             _license_info()))
    # our own custom help for all commands
    helpers.parser_add_common_opt(subparser, 'help')
    # let module configure the parser
    subcmdmod.setup_parser(subparser)
    # logger for command

    # configure 'run' function for this command
    subparser.set_defaults(func=subcmdmod.run,
                           logger=logging.getLogger('testkraut.%s' % cmd))
    # store short description for later
    sdescr = getattr(subcmdmod, 'short_description',
                     parser_args['description'].split('\n')[0])
    cmd_short_description.append((cmd_name, sdescr))

# create command summary
cmd_summary = []
for cd in cmd_short_description:
    cmd_summary.append('%s\n%s\n\n' \
                       % (cd[0],
                          textwrap.fill(cd[1], 75,
                              initial_indent=' ' * 4,
                              subsequent_indent=' ' * 4)))
parser.description = '%s\n%s\n\n%s' \
        % (parser.description,
           '\n'.join(cmd_summary),
           textwrap.fill("""\
Detailed usage information for individual commands is
available via command-specific help options, i.e.:
%s <command> --help""" % sys.argv[0],
                            75, initial_indent='',
                            subsequent_indent=''))

# parse cmd args
args = parser.parse_args()
# default log level
args.common_log_level = log_levels.get(args.common_log_level, logging.WARNING)
# configure the loggers
lgr.setLevel(args.common_log_level)
args.logger.setLevel(args.common_log_level)
# run the function associated with the selected command
try:
    args.func(args)
except Exception as exc:
    logging.error('%s (%s)' % (str(exc), exc.__class__.__name__))
    if args.common_debug:
        raise
    sys.exit(1)
