#!/usr/bin/env python

import os
from os import path
import sys
import re

#
# check arguments
#
if len(sys.argv) < 2:
    print 'Usage: %s GENERIC_LIBRARY_PATH [SOURCE_DIR_OR_FILE ...]' % sys.argv[0]
    quit()

gen_lib_path = sys.argv[1]
gen_lib_basename = os.path.basename( gen_lib_path )
if len(sys.argv) == 2:
    source_paths = ['.'];
else:
    source_paths = sys.argv[2:]


#
# scan generic_library directory to create a set of header files
#
def get_header_dictionary( gen_lib_path ):
    gen_lib_src_path = path.join(gen_lib_path, 'src')
    header_dict = {}

    if not path.isdir( gen_lib_src_path ):
        sys.stderr.write( 'error: \'%s\' is not a valid generic_library directory.\n' % gen_lib_path )
        quit()

    for module in os.listdir( gen_lib_src_path ):
        include_dir = path.join( gen_lib_src_path, module, 'include' )
        if path.isdir( include_dir ):
            for header_file in os.listdir( path.join(gen_lib_src_path, module, 'include' ) ):
                header_dict[header_file] = module
    return header_dict

header_dict = get_header_dictionary( gen_lib_path )


#
# check 'include' directive in sources and create a set of used library
#
regexp = re.compile('^\s*#\s*include\s*["<]([^">]+)[">]\s*(//.*)?$')

used_lib_set = set()

def add_used_lib_set( path ):
    for line in open( path, 'r' ):
        matched = regexp.match( line )
        if matched:
            header_name = matched.group(1)
            if header_name in header_dict:
                used_lib_set.add( header_dict[header_name] )

for src in source_paths:
    if not path.isdir( src ):
        add_used_lib_set( src )
    else:
        for dir, child_dirs, child_files in os.walk( src ):
            # skip directories for revision control
            if '.svn' in child_dirs: child_dirs.remove('.svn')
            if '.hg' in child_dirs:  child_dirs.remove('.hg')
            if '.git' in child_dirs: child_dirs.remove('.git')
            if '.bzr' in child_dirs: child_dirs.remove('.bzr')
            if '_darcs' in child_dirs: child_dirs.remove('_darcs')
    
            if gen_lib_basename in child_dirs:
                if path.samefile( path.join(dir, gen_lib_basename), gen_lib_path ):
                    child_dirs.remove( gen_lib_basename )
    
            for file in child_files:
                add_used_lib_set( os.path.join(dir, file) )

#
# check 'include' directive in sources
#
print ' '.join( sorted(used_lib_set) )
