#!/usr/bin/python
# This file is in RCS
import os, httplib, sys, cgitb

idsfile = "/tmp/sourceforge-ids.txt"
precomputed = "/usr/local/www/www.python.org/sourceforge-ids.txt"

def num():
    try:
        return int(os.environ['PATH_INFO'][1:])
    except (KeyError, ValueError, TypeError):
        try:
            import cgi
            return int(cgi.FieldStorage().getvalue("id"))
        except (ValueError, TypeError):
            return None

def bad_request(msg):
    print "Content-type: text/html"
    print ""
    print "<html><title>Invalid report</title>"
    print "<body>"+msg+"</body></html>"
    raise SystemExit

def log_type(id, type):
    created = 0
    try:
        for i in range(10):
            try:
                f = os.open(idsfile+".lck",os.O_WRONLY|os.O_CREAT|os.O_EXCL)
            except:
                os.sleep(0.1)
            else:
                os.close(f)
                break
        else:
            return # could not get lock
        f = open(idsfile,"a+")
        f.write("%d %s\n" % (id, type))
        f.close()
    finally:
        os.unlink(idsfile+".lck")

report = num()
if not report:
    bad_request("You did not provide a report number")

if not os.path.exists(idsfile) and os.path.exists(precomputed):
    os.umask(022)
    open(idsfile,"w").write(open(precomputed).read())

try:
    file = open(idsfile).readlines()
except:
    file = []

for line in file:
    num, tracker = line.split()
    if int(num) == report:
        break
else:
    tracker = None

short_template = "/tracker/index.php?func=detail&aid=%d&group_id=5470&atid=%s"
template = "http://sourceforge.net" + short_template
trackers = ['105470','305470','355470']

location = None
if tracker:
    location = template % (report, tracker)
else:
    for tracker in trackers:
        h = httplib.HTTPConnection('sourceforge.net')
        h.connect()
        h.putrequest("GET", short_template % (report, tracker))
        h.endheaders()
        r = h.getresponse()
        if r.status != 200:
            continue
        elif r.read().find("[ %d ]" % report) != -1:
            location = template % (report, tracker)
            log_type(report, tracker)
            break
        else:
            continue
    else:
        bad_request("The requested report is neither bug, patch, nor feature request")

print "Location: "+location+"\n"

