#!/usr/bin/python
import os, os.path, commands
import formatter, StringIO

PYTHON_VERSIONS=['2.3']
PYTHON_VERSION_DEFAULT='2.3'
PYTHON_VERSION_TOOBIG='2.4'

def reflow(s):
    out=StringIO.StringIO()
    w=formatter.DumbWriter(out)
    for para in s.split('\n\n'):
	if para[:1]==' ':
	    w.send_literal_data(para)
	else:
	    w.send_flowing_data(para)
	    w.send_literal_data('\n')
	w.send_paragraph(1)

    l=[]
    for line in out.getvalue().split('\n'):
	if line=='':
	    l.append(' .')
	else:
	    l.append(' '+line)
    while l and l[-1]==' .':
	del l[-1]
    return '\n'.join(l)


class CmdDict(object):
    def __init__(self, setup=None, **kwargs):
	self.setup=setup
	self.vars=kwargs

    def handle_var(self, var):
	return self.vars[var]

    def handle_setup(self, cmd):
	assert self.setup
	return self.handle_shell('python %s %s'%(self.setup, cmd))

    def handle_extract_setup_var(self, var):
	"""Extract a variable from a comment inside the setup file."""
	assert self.setup
	f=open(self.setup)
	start="#%s:" % var
	for line in f.xreadlines():
	    line=line.strip()
	    if line.startswith(start):
		line=line[len(start):].strip()
                # allow the line to contain %-magic, too
                line = line % self
		return line
	raise 'No special variable %s in setup file %s' \
	      % (repr(var), self.setup)

    def handle_shell(self, cmd):
	status, output = commands.getstatusoutput(cmd)
	if status:
	    raise 'Command %s failed with exit status %d.' \
		  % (repr(cmd), status)
	return output

    def handle_forpython(self, s):
	l=[]
	for pyver in PYTHON_VERSIONS:
	    l.append(s % pyver)
	return ', '.join(l)

    def __getitem__(self, s):
	first, rest = s.split(None, 1)
	f=getattr(self, 'handle_'+first.replace('-', '_'))
	return f(rest)

    def handle_depends(self, s):
        s1 = '%(extract-setup-var debian-depends)s' % self
        s2 = ', '.join(self.vars['depends']) % self
        s = ', '.join([x for x in [s1, s2] if x])
        return s


PACKAGE_TEMPLATE = """
Package: %(var package)s
Section: %(extract-setup-var debian-section)s
Architecture: all
Depends: %(depends foo)s
Description: %(setup --description)s
"""
def printPackage(name,
                 setupName,
                 depends=[],
                 descriptionFooter=None,
                 **kwargs):
    c = CmdDict(setupName,
                package=name,
                PYTHON_VERSION_DEFAULT=PYTHON_VERSION_DEFAULT,
                PYTHON_VERSION_TOOBIG=PYTHON_VERSION_TOOBIG,
                depends=depends,
                **kwargs)
    print PACKAGE_TEMPLATE.strip() % c
    print reflow('%(setup --long-description)s' % c)
    if descriptionFooter is not None:
	print ' .'
	print descriptionFooter % c
    print

printed_source=0
files = os.listdir('.')
files.sort()
for filename in files:
    if not filename.startswith('setup-') \
       or not filename.endswith('.py'):
	continue
    if not printed_source:
	printed_source=1
	print """\
Source: %(shell dpkg-parsechangelog|sed -n 's/^Source: //p')s
Section: %(extract-setup-var debian-section)s
Priority: optional
Maintainer: %(setup --contact)s <%(setup --contact-email)s>
Standards-Version: 3.5.6
Build-Depends-Indep: %(forpython python%s-dev)s, debhelper (>= 4.1.68), docbook-slides (>= 3.2.0), xsltproc, source-highlight, python2.3-epydoc, dia (>= 0.93-2)
""" % CmdDict(filename)
    package=filename[len('setup-'):-len('.py')]

    if package.startswith('python-'):
        printPackage(package, filename,
                     depends=[
            'python (>= %(var PYTHON_VERSION_DEFAULT)s)',
            'python (<< %(var PYTHON_VERSION_TOOBIG)s)',
            'python%(var PYTHON_VERSION_DEFAULT)s-'+package[len('python-'):],
            ],
                     descriptionFooter='''\
 This is a dummy package that depends on the correct version of
 %(var package)s for the default version of Python.
'''.rstrip(),
                     python_version='',
                     )

	for pyver in PYTHON_VERSIONS:
            printPackage('python'+pyver+'-'+package[len('python-'):],
                         filename,
                         depends=['python%(var python_version)s'],
                         python_version=pyver,
                         descriptionFooter="""\
 This version is usable with python%(var python_version)s
 """.rstrip(),
                         )
    else:
        printPackage(package, filename,
                     depends=[
            'python (>= %(var PYTHON_VERSION_DEFAULT)s)',
            'python (<< %(var PYTHON_VERSION_TOOBIG)s)',
            'python%(var PYTHON_VERSION_DEFAULT)s-ldaptor',
            ])

print '''\
Package: ldaptor-doc
Section: doc
Architecture: all
Description: Documentation for Ldaptor
 A collection of documentation about Ldaptor and LDAP, including
 .
 - An introduction to LDAP
 .
 - The Ldaptor library API
 .
 - Slides for a talk "Creating a simple LDAP application"
'''
