#!/usr/bin/env python

# Read all manifest files in a directory + Create a new file
# "Profile.mnf.xmi" that contains one Profile element. Populate the
# Profile.extensions slot with the extensions from the mnf.xmi files

# Arguments: directory that should be converted
# Example: ./addProfile.py ../../coral/addins/UML14

import sys,os
import coral

def parse_profile_name(path):
    return path.split("/")[-2]

def addEntryToProfile(entry,profile):
    # Here the extensions should be stolen from the original mnf file
    # and moved into the Profiles ownedElement
#     if not profile.ownedElement.exists(lambda e: str(entry.__type__().getName())+"s"==e.name):
#         package=coral.lang.CoralEx10.Package(name=str(entry.__type__().getName())+"s")
#         profile.ownedElement.append(package)

#     package=profile.ownedElement[str(entry.__type__().getName())+"s"]
#     package.ownedElement.append(entry)
    
    profile.extensions.append(entry)
    

def create_profile_file(profile_name,files):
     prj=coral.Project()
     prj.setFilename("Profile.mnf.xmi")
     package=coral.lang.CoralEx10.Package(name="Profile")
     profile=coral.lang.CoralEx10.Profile(name=profile_name,owner=package)
     package.__setProject__(prj)

     for mnf in files:
         loaded_prj=coral.loadDocument(mnf)
         for elem in loaded_prj.contents():
             for part in elem.__getAllParts__():
                 if part.oclIsKindOf(coral.lang.CoralEx10.Addins.ExtEntry):
                     addEntryToProfile(part,profile)
        
     coral.saveDocument(prj)

if __name__=="__main__":
    if len(sys.argv)<2:
        print "Not enough arguments"
        sys.exit(1)

    if not os.path.isdir(sys.argv[1]):
        print "Not a directory"
        sys.exit(2)

    path=sys.argv[1]
    mnf_files=[]
    for mnf in os.listdir(path):
        if mnf[-8:]==".mnf.xmi" and mnf != "Profile.mnf.xmi":
            mnf_files.append(mnf)
            
    if path[-1]!="/": path+="/"
    
    if mnf_files:
        print "OK"
        print "using ",mnf_files
        print "to create Profile.mnf.xmi",
        print "in ", path
    else:
        print "No input files found,\nexiting"
        sys.exit(0)
        
    os.chdir(path)
    create_profile_file(parse_profile_name(path),mnf_files)
