#!/usr/bin/env python3
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4; encoding:utf8 -*-
#
# Copyright 2002 Ben Escoto <ben@emerose.org>
# Copyright 2007 Kenneth Loafman <kenneth@loafman.com>
#
# This file is part of duplicity.
#
# Duplicity is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# Duplicity is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with duplicity; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

from __future__ import print_function
from future import standard_library
standard_library.install_aliases()

import os
import re
import shutil
import time
import sys
from subprocess import Popen, PIPE

sys.path.insert(0, os.path.abspath(u"./"))

from duplicity import __version__

git = Popen(u"git rev-parse --short=8 HEAD".split(), stdout=PIPE, universal_newlines=True)
revno = git.communicate()[0].split()[0].strip()

Version = __version__ + u'+' + revno


def VersionedCopy(source, dest):
    u"""
    Copy source to dest, substituting $version with version
    $reldate with today's date, i.e. December 28, 2008.
    """
    fin = open(source, u"rt")
    inbuf = fin.read()
    assert not fin.close()

    (outbuf, cnt) = re.subn(u"\$version", Version, inbuf)

    inbuf = outbuf
    (outbuf, cnt) = re.subn(u"\$reldate", Reldate, inbuf)

    fout = open(dest, u"wt")
    fout.write(outbuf)
    assert not fout.close()


def MakeTar():
    u"""Create duplicity tar file"""
    tardir = u"duplicity-%s" % Version
    tarfile = u"duplicity-%s.tar.gz" % Version
    try:
        os.system(u"rm -rf " + tardir)
    except OSError:
        pass

    # tarball contains the entire versioned release
    os.mkdir(tardir)
    sourcefiles = list()

    # use git to get files list
    if len(sourcefiles) == 0:
        git = Popen([u"git", u"ls-files"], stdout=PIPE, universal_newlines=True)
        sourcefiles = git.communicate()[0].split()

    assert len(sourcefiles) > 0, u"No files list returned from any source."

    sourcefiles = [fn.strip() for fn in sourcefiles]

    for filename in sourcefiles:
        pname, fname = os.path.split(filename)
        pathname = os.path.join(tardir, pname)
        if not os.path.exists(pathname):
            os.makedirs(pathname)
        if fname:
            assert not os.system(u"cp -p %s %s" % (filename, pathname)), fname + u" to " + pathname

    # msgfmt the translation files that we have for release
    assert not os.system(u"cd po && ./update-pot")
    linguas = open(u'po/LINGUAS').readlines()
    for line in linguas:
        langs = line.split()
        for lang in langs:
            assert not os.mkdir(os.path.join(tardir, u"po", lang)), lang
            assert not os.system(u"cp po/%s.po %s/po/%s" % (lang, tardir, lang)), lang
            assert not os.system(u"msgfmt po/%s.po -o %s/po/%s/duplicity.mo" % (lang, tardir, lang)), lang

    # make sure executables are
    os.chmod(os.path.join(tardir, u"setup.py"), 0o755)
    os.chmod(os.path.join(tardir, u"bin", u"duplicity"), 0o755)
    os.chmod(os.path.join(tardir, u"bin", u"rdiffdir"), 0o755)

    # recopy the unversioned files and add correct version
    VersionedCopy(os.path.join(u"bin", u"duplicity.1"),
                  os.path.join(tardir, u"bin", u"duplicity.1"))
    VersionedCopy(os.path.join(u"bin", u"rdiffdir.1"),
                  os.path.join(tardir, u"bin", u"rdiffdir.1"))
    VersionedCopy(os.path.join(u"snap", u"snapcraft.yaml"),
                  os.path.join(tardir, u"snap", u"snapcraft.yaml"))
    VersionedCopy(u"setup.py",
                  os.path.join(tardir, u"setup.py"))

    # set COPYFILE_DISABLE to disable appledouble file creation
    os.environ[u'COPYFILE_DISABLE'] = u'true'

    # make the tarball and clean up
    os.system(u"tar -czf %s %s" % (tarfile, tardir))
    shutil.rmtree(tardir)
    return tarfile

def Main():
    print(u"Processing version " + Version)
    tarfile = MakeTar()
    print(u"Made tar file " + tarfile)

if __name__ == u"__main__" and u'__no_execute__' not in globals():
    if len(sys.argv) != 1:
        print(u"Syntax: makedist")
        sys.exit(1)
    Reldate = time.strftime(u"%B %d, %Y", time.localtime())
    Main()
