#!/usr/bin/env python3
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# 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, STDOUT
sys.path.insert(0, os.path.abspath(u"./"))

from duplicity import util

SourceDir = u"duplicity"


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)
    testfiles = list()

    # use dist/relfiles.txt as files list
    dist = os.path.dirname(sys.argv[0])
    relfiles = os.path.join(dist, u"relfiles.txt")
    if os.path.exists(relfiles):
        testfiles = open(relfiles).readlines()

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

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

    # got files list so save it
    if len(testfiles) > 0:
        open(relfiles, u"wt").writelines(testfiles)

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

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

    for filename in testfiles:
        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

    # recopy the versioned files and add correct version
    VersionedCopy(os.path.join(SourceDir, u"globals.py"),
                  os.path.join(tardir, u"duplicity", u"globals.py"))
    VersionedCopy(os.path.join(u"bin", u"duplicity"),
                  os.path.join(tardir, u"bin", u"duplicity"))
    VersionedCopy(os.path.join(u"bin", u"rdiffdir"),
                  os.path.join(tardir, u"bin", u"rdiffdir"))
    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"))

    # 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)

    # 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) != 2:
        print(u"Syntax: makedist <version_number>")
        sys.exit(1)
    Version = sys.argv[1]
    Reldate = time.strftime(u"%B %d, %Y", time.localtime())
    Main()
