print("Hello")

import sys
import socket
import os
import getopt
import subprocess
import re
import shutil
#import svn.remote

_prgName=os.path.basename(sys.argv[0])
_prgDir=os.path.dirname(sys.argv[0])
_hostName = socket.gethostname()
_homeDir = os.getenv("HOME")
_wsHomeDir = = os.getenv("WS")
_wsDir = _wsHomeDir + r'/MDM-LCAG-JavaFunctions'
_codeURL = 'https://w-app01-d01.az.lhgroup.de/svn/talend_projects/LC_MDM/trunk/code/routines'

# Options
_options="h"

# Option handling variables
#_optLogDir = _optTmpDir

def usage(status):
    global _prgName

    USAGE = "Usage: " + _prgName + " [options] <source directory> "
    USAGE += """
Options:
   -h:            help = print this usage
   -f <filter>    use only file that match the filter (default: .pdf)
   -t <target>    use <target> as the target directory
   -v:            verbose

Description:
   Rename artificial file names in a <source directory>, allow to rename them and move them to a target directory.
   Lists the <scan directory> file by file, and shows the target directory tree.
Arguments:
   none
Examples:
"""
    print(USAGE)
    #print("Version:      " + getVersion())
    print("Status:       " + str(status))
    sys.exit("Exit on Error")


def svnInfo(fileURL):
    info = subprocess.check_output("svn info " + fileURL, shell=True).decode('utf-8')
    props = info.splitlines()
    result = dict()
    
    for p in props:
        #print(p)
        if p.strip() == "": continue
        
        key, value = re.split("^\s*([\w\s]+):\s+(.+)\s*$", p)[1:-1]
        result[key] = value
        
    return result
    
def svnDir(dirURL):
    result = subprocess.check_output("svn list " + dirURL, shell=True)
    result = result.decode('utf-8')
    lines = result.splitlines()
    
    return lines

def svnCheckout(dirURL, aFileName, asFile =None):
    result = subprocess.check_output("svn up %s" % (aFileName), shell=True)   
    result = result.decode('utf-8').strip()
    
    if asFile != None:
        result = shutil.copy(aFileName, asFile)
        print("SVN Checked out: %s --> %s" % (aFileName, asFile))
    else: 
        print("SVN Checked out: %s" % (aFileName))

    return result

def processDir(codeURL, codeTargetDir):
    cwd = os.getcwd()
    os.chdir(codeTargetDir)
    
    result = subprocess.check_output("svn co %s --depth empty" % (codeURL), shell=True)
    dir = os.path.basename(codeURL)

    os.chdir(dir)

    fileList = svnDir(codeURL)
    fileList.sort()
    
    currentFile = None
    fileVersions=dict()
    
    for f in fileList:
        fileName, ext = os.path.splitext(f)
        if ext != ".item": continue
        
        versionIndex = fileName.rindex('_')
        if versionIndex > 0:
            name = fileName[:versionIndex]
            version = fileName[versionIndex+1:]
        else:
            name = fileName
            version=""
    
        infos = svnInfo("/".join([codeURL, f]))
        rev = int(infos["Last Changed Rev"])
        
        if name in fileVersions:
            fileVersions[name][rev] = version
        else:
            fileVersions[name] = dict()
            fileVersions[name][rev] = version
                
    
    for f in fileVersions.keys():
        newest = max(fileVersions[f].keys())
        fileName = "%s_%s.item" % (f, fileVersions[f][newest])
        fileURL = "%s/%s" % (codeURL, fileName)
        javaFile = "../%s.java" % (f)
        
        svnCheckout(codeURL, fileName, javaFile)

 
    os.chdir(cwd)
    
# ---------------------------------------------------------------------------
# Main program
# ---------------------------------------------------------------------------
def main(argv):
    global _options, _wsDir, _codeURL

    try:
        opts, args = getopt.getopt(argv[1:], _options)
    except getopt.GetoptError as err:
        usage(err)

    # Handle Options:
    for opt, arg in opts:
        arg = arg.strip()

        if opt == "-h":
            usage("OK")

    if len(args) > 0:
        _wsDir = args[0]
        pass

    #curTime = datetime.now().strftime("%d %b %Y, %H:%M:%S")
    print("WS: " + _wsDir)
    codeTargetDir = os.path.join(_wsDir, "src", "main", "java", "routines")
    
    for d in ["LCAG", "CIMT_Framework"]:
        codeURL = "/".join([_codeURL, d])
        processDir(codeURL, codeTargetDir)
        
    print("Copying done, all up to date")

if __name__ == "__main__":
    print("copynewest.py started!")
    sys.exit(main(sys.argv))

