import os
import re

version_re = re.compile(r'''version\s*=\s*['"](?P<version>[\d\.]+)['"]''')

def get_launchpad():
    from launchpadlib.launchpad import Launchpad
    from launchpadlib.credentials import Credentials
    from launchpadlib.launchpad import EDGE_SERVICE_ROOT
    cachedir = os.path.expanduser('~/.launchpad-cache')
    if not os.path.exists(cachedir):
        os.mkdir(cachedir)
    credentials = Credentials()
    credentials.load(open(os.path.expanduser("~/.launchpad")))
    return Launchpad(credentials, EDGE_SERVICE_ROOT, cachedir)

def get_version():
    """Extract the current version from the setup.py file."""
    setup = open('setup.py').read()
    return version_re.search(setup).group('version')

def release_installation_template():
    """Release the installation template."""
    from launchpadlib.errors import HTTPError

    version = get_version()
    set(distdir='dist/wheeljack-install', version=version)
    trunk = 'https://api.edge.launchpad.net/beta/wheeljack/trunk/'

    local('mkdir -p dist')
    local('rm -rf $(distdir)')
    local('rm -rf $(distdir)-export')
    local('bzr export $(distdir)-export')
    local('cp -R $(distdir)-export/examples/buildout-install $(distdir)')
    local('cd dist; tar cfz wheeljack-install.tgz wheeljack-install')
    # Upload the release to Launchpad.
    launchpad = get_launchpad()
    try:
        #  First try to get an existing release.
        release = launchpad.load(trunk + version)
    except HTTPError:
        # If it does not exist we will create one.
        release = launchpad.load(trunk).addRelease(version=version)

    # Try to delete an existing download
    try:
        download = launchpad.load(
            trunk + version + '/+file/wheeljack-install.tgz')
    except HTTPError:
        pass
    else:
        # Workaround for a Launchpadlib bug
        try:
            download.delete()
        except HTTPError:
            pass

    file_content = open('dist/wheeljack-install.tgz', 'rb').read()
    release.add_file(filename='wheeljack-install.tgz',
                     file_content=file_content,
                     content_type='application/x-tar-gz')


def release_wheeljack():
    """Release Wheeljack to PyPi."""
    version = get_version()
    test()
    local('python2.5 setup.py sdist')
    # Make sure we have a proper release that could be installed.
    local('tar xfz %s/dist/wheeljack-%s.tar.gz -C /tmp' % (
            os.path.abspath('.'), version))
    local('cd /tmp/wheeljack-$(version); python2.5 setup.py egg_info')
    # Release the code.
    local('python2.5 setup.py sdist register upload')


def release():
    """Release everything related to the project."""
    release_installation_template()
    release_wheeljack()

def test():
    """Create an in-place installation and run the tests."""
    local('python2.5 bootstrap.py')
    local('./bin/buildout -v')
    local('./bin/test')

def debian():
    """Create a Debian package."""
    version = get_version()
    set(version=version)
    set(orig='dist/debian/wheeljack_$(version).orgig.tar.gz')
    local('python2.5 setup.py sdist')
    local('mkdir -p dist/debian')
    local('mv dist/wheeljack-$(version).tar.gz $(orig)')
    local('tar xfz $(orig) -C dist/debian')
    local('cp -R debian dist/debian/wheeljack-$(version)/debian')
    local('cd dist/debian/wheeljack-$(version) && dpkg-buildpackage -us -uc')
