#!/usr/bin/python3
# 
# Program to search the ${OCSSW}/src directory
# and look for lib* subdirectories then looks in each non-lib*
# subdirectory for a CMakeLists.txt file.  If there is one
# it will search it to see if that library is being used 
# in the linker in any of the programs compiled under that
# directory.
#        R.Healy 5/4/2015


import os, re

def getLibList(tab,cmfile,cmfile_root):
    if os.path.exists(cmfile):
        f = open(cmfile)
        line = f.readline()
        pattern = re.compile('target_link_libraries')
        progs=[]
    
        while line:
            if re.search(pattern,line):
                prog = line.split("(")
                progs.append(prog[1].strip())
#                print()
                cmlname = cmfile.split('/')
                cml = len(cmlname)
                print(tab + "|" + prog[1].strip()+":" + " (" + cmlname[cml-2] + ")")
                line = f.readline()
                pattern2 = re.compile('\)')
                comment = re.compile('^#')
                while not re.search(pattern2,line):
                    if not re.search(comment,line):
                        if os.path.exists(cmfile_root + "lib" + line.strip()):
                            if len(tab) < 20:
                                subcmfile = cmfile_root + "lib" + line.strip() + "/CMakeLists.txt"
                                getLibList(tab + "|   ",subcmfile,cmfile_root)
                            else:
                                print(tab + "|  **" +line.strip()+ "(" + cmlname[cml-2] + ")")
                             
                        else:
                            print(tab + "|  ->" +line.strip()+ " (" + cmlname[cml-2] + ")")
    
                            
                    line = f.readline()
                    
            line = f.readline()
    else:
        print('nope')
        f.close()

def getLibs(dirs):
    
    import sys
    try:
        ocssw_root=os.environ['OCSSWROOT']
    except KeyError as e:
        #print("Key error ({0}): message:{1}".format(e.errno, e.strerror))
        print("OCSSWROOT environment variable not set",e)
        sys.exit()
        
    os.chdir(ocssw_root + "/src")
    path = ocssw_root + "/src"
    if not dirs:
        dirs = os.listdir( path )
        
    for drr in dirs:
        if os.path.isdir(os.path.join(path, drr)):
            print( drr + ":")
            #if not re.search(pattern2,drr2):
            cmfile_root = ocssw_root + '/src/' 
            cmfile      = ocssw_root + '/src/' + drr + '/CMakeLists.txt' 
            getLibList("    ",cmfile,cmfile_root)
                
        sys.exit()
                
def main():
    import argparse
    parser = argparse.ArgumentParser(description='Get OCSSW library dependencies.',add_help=True)

    parser.add_argument('dir', nargs=1, default=None,help=' specify an ocssw build subdirectory, otherwise all are traversed\n in the ${OCSSW}/src directory.')
#    args=parser.parse_args('l2gen'.split())
    args=parser.parse_args()
    
    dirs = args.dir[0]
    
    getLibs([dirs,])
                            
if __name__ == "__main__": main()
