#!/usr/bin/python
import copy, getopt, re, subprocess, sys, tarfile, urllib2
from os.path import dirname

default_exclude = re.compile(r'^/debian(/|$)|/\.git').search

def main():
    opts, (target,) = getopt.getopt(sys.argv[1:], 'f:x:')
    opts = dict(opts)
    pkg, ver, rev = re.match(r"(.+)_(.+g([0-9a-z]{7,}))\.orig\.tar\.xz",
                             target).groups()
    prefix = pkg + '-' + ver
    try: # first try from local working copy
        src = tarfile.open(fileobj=subprocess.Popen(
            ("git", "archive", "--format=tar", "--prefix=./", rev),
            stdout=subprocess.PIPE, cwd=dirname(dirname(__file__)),
            ).stdout, mode="r|")
    except (OSError,           # git not installed
            tarfile.ReadError, # not a working copy, revision not found, etc.
            ):                 # fallback to given url
        if '-f' not in opts:
            raise
        url = opts['-f'] % rev
        sys.stderr.write("Fall back to %s\n" % url)
        src = tarfile.open(fileobj=urllib2.urlopen(url), mode="r|*")
    try:
        exclude = re.compile(opts['-x']).search
    except KeyError:
        exclude = lambda _: False
    strip = len(src.firstmember.name)
    with open(target, 'wb') as f:
        xz = subprocess.Popen(("xz", "-c"), stdin=subprocess.PIPE, stdout=f)
        try:
            dst = tarfile.open(fileobj=xz.stdin, mode="w|")
            for item in src:
                name = item.name[strip:]
                if default_exclude(name) or exclude(name):
                    continue
                new_item = copy.copy(item)
                new_item.name = prefix + name
                dst.addfile(new_item, src.extractfile(item)
                                      if item.isreg() else None)
            del src
            dst.close()
        finally:
            xz.stdin.close()
            xz.wait()

if __name__ == '__main__':
    sys.exit(main())
