def reorder(first, start, end, placeholder=300001):
    #pmig = phabdb.phdb(db=config.bzmigrate_db,
    #                   user=config.bzmigrate_user,
    #                   passwd=config.bzmigrate_passwd)

    # range of issues to renumber
    issues = range(int(start), int(end) + 1)
    first_issue = issues[0]
    # number to start new linear renumber at
    newid = int(first)
    print 'starting renumbering at %s with %s' % (first, first_issue)
    pphid = phabdb.get_task_phid_by_id(placeholder)
    if pphid:
        print "placeholder %s not empty (%s)" % (placeholder, pphid)
        return 


    for t in issues:
        print "Reassigning reference: %s to %s" % (t, newid)
        # Find PHID of the first ticket in our lineup
        ref = bzlib.prepend + str(t)
        phid = phabdb.reference_ticket(ref)
        if len(phid) > 1 or not phid:
            newid += 1
            print 'skipping phid %s' % (ref,)
            continue
        else:
            refphid = phid[0]
        print "Reference %s is %s" % (ref, refphid)
        tid = phabdb.get_task_id_by_phid(refphid)
        print "Reference %s is starting at id %s" % (ref, tid)
        existing_task = phabdb.get_task_phid_by_id(int(newid))
        print "Existing task returns %s" % (existing_task,)
        if existing_task:
            print "Squatter task at %s is %s" % (newid, existing_task)
            print "Moving squatter %s to %s" % (existing_task, placeholder)
            phabdb.set_task_id(placeholder, existing_task)      
        phabdb.set_task_id(newid, refphid)
        if existing_task:
            print "fixup setting squatter %s to %s" % (existing_task, tid)
            phabdb.set_task_id(tid, existing_task)
        newid += 1
 def extref(ticket):
     refid = phabdb.reference_ticket("%s%s" % (rtlib.prepend, ticket))
     if not refid:
         return ''
     return refid[0]
 def get_ref(id):
     refexists = phabdb.reference_ticket('%s%s' % (bzlib.prepend,
                                                   id))
     if refexists:
         return refexists[0]
def fetch(PHABTICKETID):

    PHABTICKETID = int(PHABTICKETID)

    parser = ConfigParser.SafeConfigParser()
    parser_mode = 'phab'
    parser.read(configfile)
    phab = Phabricator(parser.get(parser_mode, 'username'),
                       parser.get(parser_mode, 'certificate'),
                       parser.get(parser_mode, 'host'))

    #dummy instance of phabapi
    phabm = phabmacros('', '', '')
    phabm.con = phab

    pmig = phabdb.phdb(db='fab_migration')

    issue = pmig.sql_x("SELECT id FROM fab_meta WHERE id = %s", PHABTICKETID)
    if not issue:
        log('%s not present for migration' % (PHABTICKETID,))
        return True

    exists = phabdb.reference_ticket('%s%s' % (fablib.prepend, PHABTICKETID))
    if exists:
        log('reference ticket %s already exists' % (PHABTICKETID,))
        return True

    tid, import_priority, header, com, created, modified = pmig.sql_x("SELECT * FROM fab_meta WHERE id = %s", PHABTICKETID)

    vlog('priority: %d' % (import_priority,))

    tinfo = json.loads(header)
    comments = json.loads(com)

    proj_phids = []
    for pn in tinfo['xprojects']:
        proj_phids.append(phabm.ensure_project(pn))
    vlog(proj_phids)
    priorities = {"Unbreak Now!": 100,
                  "Needs Triage": 90,
                  "High": 80,
                  "Normal": 50,
                  "Low": 25,
                  "Needs Volunteer": 10,
                  0: 10,
                  '0': 10}

    newticket =  phab.maniphest.createtask(title=tinfo['title'],
                                 description=tinfo['description'],
                                 projectPHIDs=proj_phids,
                                 priority=priorities[tinfo['priority']],
                                 auxiliary={"std:maniphest:external_reference":"fl%s" % (PHABTICKETID,)})

    phabdb.set_task_ctime(newticket['phid'], tinfo['dateCreated'])
    log('setting ctime of %s for %s' % (tinfo['dateCreated'], newticket['id']))
    log('Created phab ticket %s for %s' % (newticket['id'], PHABTICKETID))
    vlog(newticket)

    #  0 {'xcommenter': {u'userName': u'uvhooligan', 
    #  u'phid': u'PHID-USER-lb2dbts4cdunqxzjqf2d', 
    #  u'realName': u'Un Ver Hooligan', 
    #  u'roles': [u'unverified', u'approved', u'activated'],
    #  u'image': u'http://fabapi.wmflabs.org/res/phabricator/3eb28cd9/rsrc/image/avatar.png',
    #  u'uri': u'http://fabapi.wmflabs.org/p/uvhooligan/'}, 
    #  'created': 1409875492L, 'xuseremail': None, 
    #  'text': 'hi guys I hate email', 'last_edit': 1409875492L,
    #  'xuserphid': 'PHID-USER-lb2dbts4cdunqxzjqf2d'}
    csorted = sorted(comments.values(), key=lambda k: k['created']) 
    for k, v in enumerate(csorted):
        created = epoch_to_datetime(v['created'])
        user = v['xcommenter']['userName']
        comment_body = "**%s** wrote on `%s`\n\n%s" % (user, created, v['text'])
        vlog(phabm.task_comment(newticket['id'], comment_body))

    if tinfo["status"] == "wontfix":
        tinfo["status"] = 'resolved'

    if tinfo['status'] != 'open':
        log('set status %s' % (tinfo['status']))
        vlog(phabm.task_comment(newticket['id'], '//importing issue status//'))
        vlog(phabm.set_status(newticket['id'], tinfo['status']))

    phabdb.set_task_mtime(newticket['phid'], tinfo['dateModified'])
    log('setting modtime of %s for %s' % (tinfo['dateModified'], newticket['id']))
    pmig.close()
    time.sleep(1)
    return True