#!/usr/bin/python3
#
# Copyright © 2016 Simon McVittie
#
# Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty provided this notice is preserved.
# This file is offered as-is, without any warranty.

import argparse
import os
import shutil
import subprocess
import tempfile
from os import path

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--debian-dir', default=None)
    parser.add_argument('repository')
    parser.add_argument('revision')
    parser.add_argument('package')
    parser.add_argument('version')

    args = parser.parse_args()

    tmpdir = tempfile.mkdtemp(prefix='git-archive-orig.')

    try:
        if ':' in args.repository:
            git = '{}.git'.format(args.package)
            subprocess.check_call(['git', 'clone', '--bare', args.repository,
                    git], cwd=tmpdir)
            git = path.join(tmpdir, git)
        else:
            git = args.repository

        git_dir_env = os.environ.copy()
        git_dir_env['GIT_DIR'] = git
        subprocess.check_call(['git', 'archive',
                '-o', '{}.tar'.format(args.package),
                '--prefix={}-{}.orig/'.format(args.package, args.version),
                args.revision],
            env=git_dir_env, cwd=tmpdir)
        subprocess.check_call(['xz', '{}.tar'.format(args.package)],
                cwd=tmpdir)

        mk_origtargz = ['mk-origtargz',
                '--rename',
                '--compression=xz',
                '--directory=.',
                '--package={}'.format(args.package),
                '--version={}'.format(args.version),
                path.join(tmpdir, '{}.tar.xz'.format(args.package))]

        if args.debian_dir:
            mk_origtargz.append(
                    '--copyright-file={}/copyright'.format(args.debian_dir))

        subprocess.check_call(mk_origtargz)
    finally:
        shutil.rmtree(tmpdir)

if __name__ == '__main__':
    main()
