#!/usr/bin/python

import cgi, re, os

par = cgi.FieldStorage()

print 'Content-Type: text/html; charset="utf-8"\n\n'

basedir = 'result/'
distributions = ('utopic', 'trusty', 'saucy', 'raring', 'quantal', 'precise', 'oneiric', 'lucid')


try:
  dist = par['dist'].value
except KeyError:
  dist = 'utopic'

try:
  list = par['list'].value
except KeyError:
  list = None

try:
  arch = par['arch'].value
except KeyError:
  arch = None

try:
  package = par['package'].value
except KeyError:
  package = None

safe = re.compile('^[-a-zA-Z0-9+_.]+$')

for i in (list, dist, arch, package):
  if i and not safe.match(i):
    raise Exception('Invalid characters in parameter')

tf = open('debcheck.tmpl', 'r')
t = tf.read()
tf.close()

if list:
  if arch:
    result = 'lists/' + list + '-' + arch
  else:
    result = 'lists/' + list
elif package:
  result = 'packages/' + package.replace('.', '_')
else:
  result = 'lists/INDEX'
  list = 'INDEX'

content = 'Distribution: '
for distro in distributions:
  if distro == dist:
    content += '<em>' + dist + '</em> '
  else:
    if os.access(basedir + distro + '/' + result, os.R_OK):
      content += '<a href="%s?list=%s&amp;package=%s&amp;arch=%s&amp;dist=%s">%s</a> ' % (os.environ['SCRIPT_NAME'], list or '', package or '', arch or '', distro or '', distro or '')

content += '\n<hr>\n'

try:
  l = open(basedir + dist + '/' + result)
  content += l.read()
  l.close()
except IOError:
  content += 'Index not found. This probably means there are no packages in that category.'

t = t.replace('<%LINK%>', os.environ['SCRIPT_NAME'] + '?dist=' + dist)
t = t.replace('<%DIST%>', dist)
t = t.replace('<%CONTENT%>', content)

print t
