#!/usr/bin/env python

import os, os.path
import sys
import shutil

from twisted.python import usage

class MyOptions(usage.Options):
    optParameters = [
            ["target", "t", ""],
            ["maintainer", "m", "Andy Smith <andy@jaiku.com>"],
            ["description", "e", "foo"],
            ["long_description", "l", "bar"],
            ["debfile", "d", ""],
            ["type", "y", "python"],
            ["version", "V", "0.1"],
        ]
    optFlags = [["upload", "U", ""]]
        
    def postOptions(self):
        if not os.path.isfile(self['target']):
            raise usage.UsageError, "target is not a file"

def save(file, text):
    open(file, 'w').write(text)


def main():
    try:
        config = MyOptions()
        config.parseOptions()
    except usage.error, ue:
        sys.exit("%s: %s" % (sys.argv[0], ue))

    head, tail = os.path.split(config['target'])
    name, ext = os.path.splitext(tail)
    config['name'] = name
    config['basefile'] = tail
    config['debfile'] = name
    config['python_version'] = '%s.%s' % sys.version_info[:2]
    config['date'] = os.popen('822-date').read().strip()


    try:
        # figure out some info about the file
        sys.path = [head] + sys.path

        mod = __import__(name)

        config.update({
                "version": getattr(mod, "VERSION", "0.1"),
                "description": getattr(mod, "DESCRIPTION", "foo"),
                "long_description": getattr(mod, "LONG_DESCRIPTION", "bar"),
            })
    except:
        pass


    import commands
    svn_rev = commands.getoutput("svn info | grep Revision: | sed 's/.* //g'")

    config['version'] += "+r%s"%(svn_rev)

    config['long_description'] = config['long_description'].strip().replace("\n\n", "\n").replace("\n", "\n ")


    # generate a python module directory structure
    builddir = os.path.join("build", "%s-%s" % (name, config['version']))
    shutil.rmtree(os.path.join(builddir), True)

    debdir = os.path.join(builddir, "debian")
    
    os.makedirs(debdir)
    
    # copy the service file into it
    shutil.copy(config['target'], builddir) 
    
    # start building the debian files

    save(os.path.join(debdir, "README.Debian"), """\
/etc/init.d/%(debfile)s
/etc/default/%(debfile)s
/etc/%(basefile)s
""" % config)
    
    save(os.path.join(debdir, 'default'), """\
pidfile=/var/run/%(debfile)s.pid
rundir=/var/lib/%(debfile)s/
file=/etc/%(basefile)s
logfile=/var/log/%(debfile)s.log
""" % config)

    save(os.path.join(debdir, 'init.d'), """
#!/bin/sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin

pidfile=/var/run/%(debfile)s.pid \
rundir=/var/lib/%(debfile)s/ \
file=/etc/%(basefile)s \
logfile=/var/log/%(debfile)s.log

[ -r /etc/default/%(debfile)s ] && . /etc/default/%(debfile)s

test -x /usr/bin/twistd || exit 0
test -r $file || exit 0
test -r /usr/share/%(debfile)s/package-installed || exit 0


case "$1" in
    start)
        echo -n "Starting %(debfile)s: twistd"
        start-stop-daemon --start --quiet --exec /usr/bin/twistd -- \
                          --pidfile=$pidfile \
                          --rundir=$rundir \
                          --%(type)s=$file \
                          --logfile=$logfile
        echo "."	
    ;;

    stop)
        echo -n "Stopping %(debfile)s: twistd"
        start-stop-daemon --stop --quiet  \
            --pidfile $pidfile
        echo "."	
    ;;

    restart)
        $0 stop
        $0 start
    ;;

    force-reload)
        $0 restart
    ;;

    *)
        echo "Usage: /etc/init.d/%(debfile)s {start|stop|restart|force-reload}" >&2
        exit 1
    ;;
esac

exit 0
""" % config)

    os.chmod(os.path.join(debdir, 'init.d'), 0755)

    save(os.path.join(debdir, 'postinst'), """\
#!/bin/sh
update-rc.d %(debfile)s defaults >/dev/null
invoke-rc.d %(debfile)s start
""" % config)

    save(os.path.join(debdir, 'prerm'), """\
#!/bin/sh
invoke-rc.d %(debfile)s stop
""" % config)

    save(os.path.join(debdir, 'postrm'), """\
#!/bin/sh
if [ "$1" = purge ]; then
        update-rc.d %(debfile)s remove >/dev/null
fi
""" % config)

    save(os.path.join(debdir, 'changelog'), """\
%(debfile)s (%(version)s-1) stable; urgency=low

  * Created by package-service

 -- %(maintainer)s  %(date)s

 """ % config)

    
    save(os.path.join(debdir, 'control'), """\
Source: %(debfile)s
Section: net
Priority: extra
Maintainer: %(maintainer)s
Build-Depends-Indep: debhelper
Standards-Version: 3.5.6

Package: %(debfile)s
Architecture: all
Depends: jaiku
Description: %(description)s
 %(long_description)s
""" % config)

    save(os.path.join(debdir, 'copyright'), """\
This package was auto-debianized by %(maintainer)s on
%(date)s

It was auto-generated by package-service

Copyright:

Insert copyright here.
""" % config)

    save(os.path.join(debdir, 'dirs'), """\
etc/init.d
etc/default
var/lib/%(debfile)s
usr/share/doc/%(debfile)s
usr/share/%(debfile)s
""" % config)

    save(os.path.join(debdir, 'rules'), """\
#!/usr/bin/make -f

export DH_COMPAT=1

build: build-stamp
build-stamp:
	dh_testdir
	touch build-stamp

clean:
	dh_testdir
	dh_testroot
	rm -f build-stamp install-stamp
	dh_clean

install: install-stamp
install-stamp: build-stamp
	dh_testdir
	dh_testroot
	dh_clean -k
	dh_installdirs

	# Add here commands to install the package into debian/tmp.
	cp %(basefile)s debian/tmp/etc/
	cp debian/init.d debian/tmp/etc/init.d/%(debfile)s
	cp debian/default debian/tmp/etc/default/%(debfile)s
	cp debian/copyright debian/tmp/usr/share/doc/%(debfile)s/
	cp debian/README.Debian debian/tmp/usr/share/doc/%(debfile)s/
	touch debian/tmp/usr/share/%(debfile)s/package-installed
	touch install-stamp

binary-arch: build install

binary-indep: build install
	dh_testdir
	dh_testroot
	dh_strip
	dh_compress
	dh_installchangelogs
	dh_fixperms
	dh_installdeb
	dh_shlibdeps
	dh_gencontrol
	dh_md5sums
	dh_builddeb

source diff:                                                                  
	@echo >&2 'source and diff are obsolete - use dpkg-source -b'; false

binary: binary-indep binary-arch
.PHONY: build clean binary-indep binary-arch binary install
""" % config)

    os.chmod(os.path.join(debdir, 'rules'), 0755)

    os.chdir(builddir)
    os.system('dpkg-buildpackage -rfakeroot -uc -us')

    if config['upload']:
        os.system('dput -f jaiku ../%s_%s-1_i386.changes'%(config['name'], config['version']))

if __name__ == '__main__':
    main()

    
  
