#!/usr/bin/env python3

import os
import argparse
import re
import shutil
import subprocess
import copy

def versionFromCMakeLists(filePath):
    if not os.path.exists(filePath):
        raise NameError('File path not found');

    textFile = open(filePath, 'rt');
    contents = textFile.read(2000);
    textFile.close();

    versionLines = re.findall('set\s*\(VERSION.*\)', contents, re.MULTILINE);
    # print(versionLines);

    if not len(versionLines):
        raise NameError('Failed to find VERSION statement');

    versionLine = versionLines[0];

    pattern = re.compile('set\(VERSION\s*([0-9.]+)\).*$');
    cmakeVersionNumber = "";

    match = pattern.match(versionLine);
    if match is not None:
        cmakeVersionNumber = match[1];
    else:
        raise NameError('Failed to extract VERSION number');

    # print("Version number from CMakeLists.txt: " + cmakeVersionNumber);

    return(cmakeVersionNumber);


def upstreamVersionFromDebianChangelog(projectName, filePath):
    if not os.path.exists(filePath):
        raise NameError('File path not found');

    textFile = open(filePath, 'rt');
    contents = textFile.read(100);
    textFile.close();

    patternString = "^\s*" + projectName + "\s*\(.*$";
    # print("patternString: " + patternString);

    versionLines = re.findall(patternString, contents, re.MULTILINE);
    # print(versionLines);

    if not len(versionLines):
        raise NameError('Failed to find source package version statement');

    # Only the first occurrence is the latest.
    versionLine = versionLines[0];
    # print("Version line: " + versionLine);

    pattern = re.compile("^\s*" + projectName + "\s*\((.+)\).*$");
    upstreamDebianVersionNumber = "";

    match = pattern.match(versionLine);
    if match is not None:
        upstreamDebianVersionNumber = match[1];
    else:
        raise NameError('Failed to extract upstream-debian package version');

    # print("Upstream-debian Version number from debian/changelog: " + upstreamDebianVersionNumber);

    # The string is like 4.1.0-1, but we want to separate the -1 and thus get
    # the upstream version number and the debian package version number an
    # return them into a tuple.

    pattern = re.compile("(^.*)-([0-9]{1,2})$");
    match = pattern.match(upstreamDebianVersionNumber);

    if match is not None:
        # print(match[0]);
        upstreamVersionNumber = match[1];
        # print("upstreamVersionNumber: " + upstreamVersionNumber);

        debianVersionNumber = match[2];
        # print("debianVersionNumber: " + debianVersionNumber);

        return (upstreamVersionNumber, debianVersionNumber);
    else:
        raise NameError('Failed to extract the debian package version number');

