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

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

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:
    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()
		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)

otherpackage = """
Package: %(setup --name)s
Section: %(extract-setup-var debian-section)s
Architecture: all
Depends: python (>= %(var PYTHON_VERSION_DEFAULT)s), python (<< %(var PYTHON_VERSION_TOOBIG)s), python%(var PYTHON_VERSION_DEFAULT)s-twisted
Description: %(setup --description)s
"""

pypackage = """
Package: %(setup --name)s
Section: %(extract-setup-var debian-section)s
Architecture: all
Depends: python%(var python_version)s, python%(var python_version)s-twisted (>= 1.0.2), pwgen%(var extra_depends)s
Description: %(setup --description)s
"""

filename = 'setup.py'

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
""" % CmdDict(filename)

c=CmdDict(filename,
          PYTHON_VERSION_DEFAULT=PYTHON_VERSION_DEFAULT,
          PYTHON_VERSION_TOOBIG=PYTHON_VERSION_TOOBIG,
          )
print otherpackage.strip() % c
print reflow('%(setup --long-description)s' % c)
print
