#!/usr/bin/env python3

import os
import sys
import argparse
import re
import shutil
import subprocess
import shlex
import copy

import makeOrigTarballFunctions as motf

# First of all check that we are in the development main source directory, that
# is, that the current directory contains the "debian" directory.
if not os.path.exists("debian"):
    print('''No debian directory found. Please change directory to the
    top source directory''')
    exit(1);

# The main directory will be the directory that is upstream of "development".
mainDir = os.path.normpath(os.getcwd() + "/..");
# print("mainDir:" + mainDir + "\n");

tarballDir = mainDir + "/tarballs";
buildDir = mainDir + "/build-area";
devDir = mainDir + "/development";
debianDir = devDir + "/debian";

parser = argparse.ArgumentParser()

parser.add_argument("-p", "--project", nargs=1, required = True, 
        help='''Project name, like cb2bib or msxpertsuite''');

parser.add_argument("-d", "--withDebianDir", action='store_true', 
        help='''Make sure the debian directory is exported along with the source tarball stuff.''');

parser.add_argument("-y", "--assumeYes", action='store_true', 
        help='''Assume Yes is answered.''');

args = parser.parse_args()

# project is gotten as a string list, even if it contains a single item.
projectName = args.project[0];
withDebianDir = args.withDebianDir;
# print(withDebianDir);
assumeYes = args.assumeYes;

os.chdir(devDir);

# Check that we are in the master branch or alert the user.

completedProcess = subprocess.run(["git", "status"], stdout=subprocess.PIPE)

completedProcess.check_returncode();

output = completedProcess.stdout.decode("utf-8");

# From the output, only get the name of the branch:
onBranchLines = re.findall("^On branch.*$", output, re.MULTILINE)
onBranchLine = onBranchLines[0];
# print(onBranchLine);

# Now get the branch name.
gitBranch = re.compile("^On branch ").sub('', onBranchLine)
# print(gitBranch);

# We must be on master:
if gitBranch != "master":
    print("Error: current branch is not \"master\". Please check it out first.\n");
    exit(1);

# Now check that we have a clean status:
linePattern = "nothing to commit, working tree clean";
# print(linePattern);
treeCleanLines = re.findall(linePattern, output, re.MULTILINE);
if len(treeCleanLines) == 0:
    print("Error: current branch is not clean. Please, commit first.\n");
    exit(1);

treeCleanLine = treeCleanLines[0];
# print(treeCleanLine);
if treeCleanLine != linePattern:
    print("Error: current branch is not clean. Please, commit first.\n");
    exit(1);

# Now get the VERSION of the project from the main CMakeLists.txt file. But not
# all projects do have that file. So be careful.
cmakeFilePath = devDir + "/CMakeLists.txt";
cmakeVersionNumber =  "";

if os.path.exists(cmakeFilePath):
    cmakeVersionNumber = motf.versionFromCMakeLists(cmakeFilePath);
    print("Version number from CMakeLists.txt: " + cmakeVersionNumber);

# Now get the VERSION from the debian/changelog:
(UPVER, DEBVER) = motf.upstreamVersionFromDebianChangelog(projectName,
        debianDir + "/changelog");
# print(UPVER,DEBVER);

message = "Making .tar.gz for (UPVER = {UPVER}) and (DEBVER = {DEBVER}). Is this correct ?".format(UPVER = UPVER, DEBVER = DEBVER);

answer = input(message + " (RETURN | Ctrl-C)");

if cmakeVersionNumber is not None:
    if cmakeVersionNumber != UPVER:
        answer = input('''The CMakeLists.txt-based VERSION and the
        debian/changelog-based upstream version do not match. Continue
        nonetheless? (continue | Ctrl-C):''');

        if answer != "continue":
            print("Program aborted by user\n");
            exit(1);

# We have now all the version numbers required to craft the orig tarball
# filename:

srcTarball = "{projectName}-{UPVER}.tar".format(projectName = projectName, UPVER = UPVER);
origTarball = "{projectName}_{UPVER}.orig.tar".format(projectName = projectName, UPVER = UPVER);

print("Making {tarballDir}/{srcTarball} ...\n".format(tarballDir = tarballDir,
    srcTarball = srcTarball));

prefix = "{projectName}-{UPVER}".format(projectName = projectName, UPVER = UPVER);

commandLine = '''git archive --format=tar --verbose --prefix={prefix}/ {gitBranch}'''.format(projectName = projectName, UPVER = UPVER, gitBranch = gitBranch, prefix = prefix);
print("commandLine: " + commandLine);

args = shlex.split(commandLine);

# Redirection of the git archive command to the outputFile:
outputFile = open(tarballDir + "/" + srcTarball, 'w');

completedProcess = subprocess.run(args, stdout=outputFile);
outputFile.close();
completedProcess.check_returncode();

# At this point we have the proper source tarball. Check if we have to remove
# the debian directory.

if withDebianDir == False:
    commandLine = "tar vf " + tarballDir + "/" + srcTarball + " --delete " + prefix + "/debian";
    args = shlex.split(commandLine);
    completedProcess = subprocess.run(args);
    completedProcess.check_returncode();

# Finally, compress the tar file.
commandLine = '''gzip {0}/{1}'''.format(tarballDir, srcTarball);
args = shlex.split(commandLine);
completedProcess = subprocess.run(args);
completedProcess.check_returncode();

print("\nCreated {0}/{1}.gz\n".format(tarballDir, srcTarball));

# Now create two symbolic links:

src = "{0}/{1}.gz".format(tarballDir, srcTarball);
dest = "{0}/{1}.gz".format(tarballDir, origTarball);
if os.path.exists(dest):
  os.remove(dest);
print("Creating symbolic link: " + src + " --> " + dest + "\n");
os.symlink(src, dest);

src = "{0}/{1}.gz".format(tarballDir, srcTarball);
dest = "{0}/{1}.gz".format(mainDir, origTarball);
if os.path.exists(dest):
  os.remove(dest);
print("Creating symbolic link: " + src + " --> " + dest + "\n");
os.symlink(src, dest);

