#!/usr/bin/python
#
# querybts - Examine the state of a debbugs server
#   Written by Chris Lawrence <lawrencc@debian.org>
#   (C) 1999-2001 Chris Lawrence
#
# This program is freely distributable per the following license:
#
##  Permission to use, copy, modify, and distribute this software and its
##  documentation for any purpose and without fee is hereby granted,
##  provided that the above copyright notice appears in all copies and that
##  both that copyright notice and this permission notice appear in
##  supporting documentation.
##
##  I DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
##  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL I
##  BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
##  DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
##  WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
##  ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
##  SOFTWARE.
#
# Version ##VERSION##; see changelog for revision history

import reportbug, debianbts, commands, getopt, sys, string, os, re, mailcap

try:
    import reportbug_ui_newt
    ui = reportbug_ui_newt
    ui_mode = 'newt'
##    import reportbug_ui_text
##    ui = reportbug_ui_text
except:
    import reportbug_ui_text
    ui = reportbug_ui_text
    ui_mode = 'text'

VERSION = "querybts ##VERSION##"

USAGE = ("querybts - Examine the state of a debbugs server.\n\n"
         "Usage: querybts [options] {<package> | <report number>}\n"
         "Supported options (see man page for long forms):\n"
         "  -A: Browse archived bugs.\n"
         "  -B: Specify an alternate debbugs BTS. *\n"
         "  -h: Display this help message.\n"
         "  -l: Disable LDAP access to BTSes that support it.\n"
         "  -s: Query for source packages rather than binary packages.\n"
         "  -v: Show the version number of this program.\n"
         "  -w: Use a web browser instead of the internal interface.\n"
         "\nOptions marked * take the word 'help' to list allowed options."
         )

def main():
    system = 'debian'
    archived = 'no'
    http_proxy = interface = ''
    use_browser = use_ldap = source = 0
    mirrors = None

    args = reportbug.parse_config_files()
    for option, arg in args.items():
        if option == 'system':
            system = arg
        elif option == 'ldap':
            use_ldap = arg
        elif option == 'mirrors':
            mirrors = arg
        elif option == 'ui':
            interface = arg
        elif option == 'http_proxy':
            http_proxy = arg

    try:
        (opts, args) = getopt.getopt(
            sys.argv[1:], 'AB:hlsuvw', ['help', 'version', 'no-ldap',
                                        'bts=', 'ldap', 'web',
                                        'archive=', 'source',
                                        'http_proxy=', 'proxy=',
                                        'ui=', 'interface='])
    except getopt.error, msg:
        print msg
        sys.exit(1)

    for option, arg in opts:
        if option in ('-h', '--help'):
            print USAGE
            return
        elif option in ('-v', '--version'):
            print VERSION
            return
        elif option in ('--proxy', '--http_proxy'):
            http_proxy = arg
        elif option in ('--archive', '-A'):
            archived = 'yes'
        elif option in ('-l', '--ldap'):
            use_ldap = 1
        elif option == '--no-ldap':
            use_ldap = 0
        elif option in ('-s', '--source'):
            source = 1
        elif option in ('-u', '--ui', '--interface'):
            if arg in reportbug.VALID_UIS:
                interface = arg
            elif arg == 'help':
                print 'Permitted arguments to --ui:\n'\
                      ' text: line-oriented text mode\n'\
                      ' newt: screen-oriented text mode'
                sys.exit(0)
            else:
                print "Ignoring unknown user interface %s\n" % arg
        elif option in ('-w', '--web'):
            use_browser = 1
        elif option in ('-B', '--bts'):
            if arg in debianbts.SYSTEMS.keys():
                if debianbts.SYSTEMS[arg].get('btsroot'):
                    system = arg
                else:
                    print "Queries not supported for %s BTS." % arg
                    return
            elif arg == 'help':
                print 'Permitted arguments to --bts:'
                names = debianbts.SYSTEMS.keys()
                names.sort()
                for bsys in names:
                    if debianbts.SYSTEMS[bsys].get('btsroot'):
                        print ' %-11.11s %s' % \
                              (bsys, debianbts.SYSTEMS[bsys]['name'])
                return
            else:
                print "Ignoring unknown BTS server %s." % arg

    sysinfo = debianbts.SYSTEMS[system]
    if len(args) == 0:
        print "Please specify a package or bug number."
        print "Note: most shells consider # a comment character; however, a"
        print "leading # is unneeded to specify a bug by number."
        sys.exit(1)
    elif len(args) > 1:
        print "Please specify one package or bug number."
        print "[Did you forget to put all switches before the argument?]"
        sys.exit(1)

    package = args[0]
    if use_browser:
        debianbts.launch_browser(package, system, mirrors, archived, source)
        return

    if interface:
        global ui, ui_mode
        iface = 'reportbug_ui_'+interface
        exec 'import '+iface
        ui = eval(iface)
        ui_mode = interface

    match = re.match(r'^#?(\d+)$', package)
    if match:
        report = int(match.group(1))
        return ui.show_report(report, system, use_ldap, mirrors,
                              http_proxy, queryonly=1, title=VERSION,
                              archived=archived)

    ui.handle_bts_query(package, system, use_ldap, mirrors, http_proxy,
                        queryonly=1, title=VERSION, archived=archived,
                        source=source)
    # This should be the end

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        if ui_mode == 'newt':
            print chr(27)+'c'
            os.system('stty sane; clear')
        print "querybts: exiting due to user interrupt."
    except debianbts.Error, x:
        if ui_mode == 'newt':
            print chr(27)+'c'
            os.system('stty sane; clear')
        print 'error accessing BTS: '+str(x)
    except SystemExit:
        pass
    except:
        if ui_mode == 'newt':
            print chr(27)+'c'
            os.system('stty sane; clear')
        raise
