import os
import commands
import fnmatch
import zipfile

if (os.path.exists("/tmp/testArch")):
    commands.getoutput("rm -rf /tmp/testArch")


def getAllSources(basePath):
    matches=[]
    for root, dirnames, filenames in os.walk(basePath):
        for filename in fnmatch.filter(filenames, '*'):
            matches.append(os.path.join(filename))
    return matches


def getfile(basePath, extension):
    matches=[]
    for root, dirnames, filenames in os.walk(basePath):
        for filename in fnmatch.filter(filenames, '*.'+extension):
            matches.append(os.path.join(filename))
    return matches


def unzip_file(file):
    matches=[]
    zfobj = zipfile.ZipFile(file)
    for name in zfobj.namelist():
        n=name[name.rfind('/')+1:]
        if len(n)>0:
            matches.append(n)
    return matches
    

os.makedirs("/tmp/testArch")
print "Created Path"

os.chdir("/tmp/testArch")


def testContainer():
    print "CREATING PROJECT FROM DNET-CONTAINER-ARCHETYPE"
    commands.getstatusoutput('mvn archetype:generate -DartifactId=test -DgroupId=eu.dnetlib -Dversion=1.0-SNAPSHOT -DarchetypeArtifactId=dnet-container-archetype \
                                       -DarchetypeGroupId=eu.dnetlib \
                                       -DarchetypeVersion=0.0.1-SNAPSHOT \
                                       -DarchetypeRepository=http://maven.research-infrastructures.eu/nexus/content/repositories/dnet-snapshots/  -DinteractiveMode=false ')
    print "OK"
    print "PACKAGING PROJECT"
    os.chdir("test")
    commands.getstatusoutput("mvn package")
    print "OK"
    src= getAllSources("src")
    war= unzip_file("target/"+getfile("target","war")[0])

    for source in src:
        if (source not in war):
            raise "ERRORRR"
    os.chdir("/tmp")
    commands.getoutput("rm -rf /tmp/testArch")


def testArchetype():
    print "CREATING PROJECT FROM DNET-ARCHETYPE"
    commands.getstatusoutput('mvn archetype:generate -DartifactId=test -DgroupId=eu.dnetlib -Dversion=1.0-SNAPSHOT -DarchetypeArtifactId=dnet-archetype \
                                       -DarchetypeGroupId=eu.dnetlib \
                                       -DarchetypeVersion=0.0.1-SNAPSHOT \
                                       -DarchetypeRepository=http://maven.research-infrastructures.eu/nexus/content/repositories/dnet-snapshots/  -DinteractiveMode=false ')
    print "OK"
    print "PACKAGING PROJECT"
    os.chdir("test")
    commands.getstatusoutput("mvn package")
    print "OK"
    src= getAllSources("src")
    war= unzip_file("target/"+getfile("target","jar")[0])

    for source in src:
        if (source not in war):
            raise "ERRORRR"        
    os.chdir("/tmp")
    commands.getoutput("rm -rf /tmp/testArch")

testArchetype()
print "dnet Archetype is valid"
testContainer()
print "dnet Archetype container is valid"
