#!/usr/bin/env python

import tarfile
import tempfile
import sys
import logging
import os
import re
import shutil

logging.basicConfig(format="%(asctime)s %(message)s")
LOG = logging.getLogger("root")
LOG.setLevel(logging.INFO)

OUTPUT = os.environ["OUTPUT"] if os.environ.has_key("OUTPUT") else ".."

def copy_legal_bits(src, dest):
    for fname in ["CONTRIBUTORS", "NOTICE", "LICENSE", "DISCLAIMER"]:
        shutil.copy(os.path.join(src, fname), dest)

def repack_compiler(root, top, version):
    LOG.info("Creating compiler archive...")

    package_name = "thrift-compiler_%s" % version
    sub_dir = os.path.join("compiler", "cpp")

    copy_legal_bits(
            os.path.join(root, top),
            os.path.join(root, top, sub_dir))

    files = [
        ( "configure.ac" ,"configure.ac" ),
        ( "bootstrap.sh" ,"bootstrap.sh" ),
        ( "cleanup.sh", "cleanup.sh" ),
        ( "README", "README.Thrift" ),
        ( "aclocal", "aclocal" )
            ]

    for src, target in files:
        f_src = os.path.join(root, top, src)
        f_target = os.path.join(root, top, sub_dir, target)
        if os.path.isdir(f_src):
            shutil.copytree(f_src, f_target)
        else:
            shutil.copy(f_src, f_target)

    # Strip surplus CONFIG_FILES from configure.ac
    with open(os.path.join(root, top, sub_dir, "configure.ac"), "r") as configure_ac:
        lines = configure_ac.readlines()
    with open(os.path.join(root, top, sub_dir, "configure.ac"), "w") as configure_ac:
        skip_next=False
        for line in lines:
            if "AC_CONFIG_FILES" in line:
                configure_ac.write(line)
                configure_ac.write("  Makefile\n")
                configure_ac.write("  version.h\n")
                skip_next=True
            elif skip_next and "])" in line:
                skip_next=False
                configure_ac.write(line)
            elif not skip_next:
                configure_ac.write(line)

    with tarfile.open(os.path.join(OUTPUT, "%s.orig.tar.gz" % package_name),
                      "w:gz") as archive:
        archive.add(
            os.path.join(root, top, sub_dir),
            arcname=package_name)

    LOG.info("Created compiler archive %s.orig.tar.gz", package_name)

get_toplevel = lambda p: p.split(os.sep)[0]

if __name__ == '__main__':
    name = sys.argv[3]
    version = sys.argv[2]
    root = tempfile.mkdtemp()

    LOG.info("Using working directory %s", root)

    tar = tarfile.open(name)
    manifest = tar.getnames()

    target = get_toplevel(manifest[0])
    LOG.info("Extracting %s to %s", name, target)

    tar.extractall(root)

    repack_compiler(root, target, version)

    LOG.info("Removing working directory")
    shutil.rmtree(root)
