from setuptools.command.sdist import sdist as sdist
from distutils.spawn import spawn
from distutils.dir_util import remove_tree
import os.path
import os

class sdist_deb(sdist):
    description = "create a debian package from source distro"

    def run(self):
        self.force_manifest = True
        sdist.run(self)
 
        # build up our options dict
        options = {}
        for x in ("name", "version", "maintainer", "maintainer_email",
                  "license", "description", "long_description", "platforms"):
            options[x] = getattr(self.distribution, "get_%s" % x)()
        options['deb_version'] = options['version'].replace("-", "+") + "-1"
        options['platforms'] = " ".join(options['platforms'])
        options['long_description'] = options['long_description'].strip().replace("\n\n", "\n").replace("\n", "\n ")
            
        f = [a for a in self.get_archive_files() if a.endswith(".tar.gz")]
        if not f:
            raise Exception("not a .tar.gz")
        archive_file = f[0]
    
        base_dir = self.distribution.get_fullname()
        base_name = os.path.join(self.dist_dir, base_dir)

        try:
            remove_tree(base_name)
        except:
            pass

        # extract our new friend
        cmd = ["tar", "-xzf", archive_file, "-C", self.dist_dir]
        self.spawn(cmd)

        # do the deb stuff
        os.chdir(base_name)

        dh_cmd = ["sh", "-c", 
                  " ".join(["dh_make", "-e", options['maintainer_email'], "-f",
                           os.path.join("..", "..", archive_file), "--single"])]
        
        self.spawn(dh_cmd)
        
        rules = """\
#!/usr/bin/make -f
# -*- makefile -*-
# Sample debian/rules that uses debhelper.
# This file was originally written by Joey Hess and Craig Small.
# As a special exception, when this file is copied by dh-make into a
# dh-make output file, you may use that output file without restriction.
# This special exception was added by Craig Small in version 0.37 of dh-make.

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1




CFLAGS = -Wall -g

ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
	CFLAGS += -O0
else
	CFLAGS += -O2
endif

configure: configure-stamp
configure-stamp:
	dh_testdir
	# Add here commands to configure the package.

	touch configure-stamp


build: build-stamp
	echo `pwd`
	python setup.py build

build-stamp: configure-stamp 
	dh_testdir

	touch build-stamp

clean:
	dh_testdir
	dh_testroot
	rm -f build-stamp configure-stamp

	dh_clean 

install: build
	dh_testdir
	dh_testroot
	dh_clean -k 
	dh_installdirs

	python setup.py install --root=$(CURDIR)/debian/%(name)s


# Build architecture-independent files here.
binary-indep: build install
	# We have nothing to do by default.

# Build architecture-dependent files here.
binary-arch: build install
	dh_testdir
	dh_testroot
	#dh_installchangelogs 
	#dh_installdocs
	#dh_installexamples
	#dh_install
	#dh_installmenu
	#dh_installdebconf	
	#dh_installlogrotate
	#dh_installemacsen
	#dh_installpam
	#dh_installmime
	dh_pysupport
	#dh_installinit
	#dh_installcron
	#dh_installinfo
	dh_installman
	dh_link
	dh_strip
	dh_compress
	dh_fixperms
	#dh_perl
	#dh_makeshlibs
	dh_installdeb
	dh_shlibdeps
	dh_gencontrol
	dh_md5sums
	dh_builddeb

binary: binary-indep binary-arch
.PHONY: build clean binary-indep binary-arch binary install configure
"""
        rules = rules % options
        
        # write the rules file
        open("debian/rules", "w").write(rules)
        
        # control files
        control = """\
Source: %(name)s
Section: net
Priority: extra
Maintainer: %(maintainer)s <%(maintainer_email)s>
Build-Depends: debhelper (>= 5)
Standards-Version: 3.7.2

Package: %(name)s
Architecture: %(platforms)s
Depends:
Description: %(description)s
 %(long_description)s
"""
        control = control % options
        
        # write the rules file
        open("debian/control", "w").write(control)
        
        # changelog
        changelog = """\
%(name)s (%(deb_version)s) stable; urgency=low

  * Initial release (Closes: #nnnn)  <nnnn is the bug number of your ITP>

 -- %(maintainer)s <%(maintainer_email)s>  Wed,  6 Jun 2007 05:13:39 -0700

"""
        changelog = changelog % options
        # write the changelog
        open("debian/changelog", "w").write(changelog)

        

        # build the package
        dpkg_cmd = ["sh", "-c", 
                     " ".join(["dpkg-buildpackage", "-rfakeroot", "-us", "-uc"])]
        
        self.spawn(dpkg_cmd)
