#! /usr/bin/env python

"""Enter Jitterbug reports into the SF Bug Tracker

upload.py [OPTIONS] [jitterbug_path]

This script reads Jitterbug data from its filesystem representation
and uploads each bug report to the SourceForge Bug Tracker.

Jitterbug stores each of its bug categories in a separate directory
 (e.g. open, notabug, etc.).  This script reads all of the bug files
from a single directory.  To upload an entire Jitterbug database, the
script must be run once on each directory.

The command-line options are used to specify metadata for SF.  For
each option, you must specify the SF id for the field, which you can
find by viewing the source of the standard bug submission form.

  -P [project_group_id]      which project to add bugs to (REQUIRED)
  -p [1..10]                 bug priority (default 5)
  -c [category_id]           SF bug category
  -g [group_id]              SF bug group

The -v option provides verbose output.
The -h option prints this message.
"""

import sys
import os
import re
import getopt

import jitterbuglib

VERBOSE = 0
_rx_num = re.compile('\d+$')



def find_bugs(dir):
    """Return a list of the bug ids contained in dir"""
    bug_ids = []
    for file in os.listdir(dir):
        mo = _rx_num.match(file)
        if mo:
            bug_ids.append(file)
    bug_ids.sort()
    return bug_ids



def main(dir):
    bug_ids = find_bugs(dir)
    for bid in bug_ids:
        bug = jitterbuglib.Bug(dir, bid)
        if VERBOSE:
            print "loaded PR#%s" % bid
        bug.submit(jitterbuglib.SF_SUBMIT_URL)



def usage(code, msg=''):
    print >> sys.stderr, __doc__
    if msg:
        print >> sys.stderr, msg
    sys.exit(code)



if __name__ == "__main__":
    proj_group_set = 0
    
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'P:g:vp:hc:')
    except getopt.error, msg:
        usage(1, msg)
        
    if len(args) > 1:
        usage(1, 'unexpected arguments: ' + ' '.join(args[1:]))
    if len(args) == 0:
        usage(1, 'jitterbug_path missing')

    for k, v in opts:
        if k == '-v':
            VERBOSE = 1
        elif k == '-h':
            usage(0)
        elif k == '-g':
            jitterbuglib.set_label("GROUP", v)
        elif k == '-p':
            jitterbuglib.set_label("PRIORITY", v)
        elif k == '-P':
            jitterbuglib.set_label("PROJECT_GROUP_ID", v)
            proj_group_set = 1
        elif k == '-c':
            jitterbuglib.set_label("CATEGORY", v)

    if not proj_group_set:
        usage(1, '-P option is required')

    # all's well
    main(args[0])
