# determine path to here, package name
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os


def rreplace(s, old, new, occurrence):
    li = s.rsplit(old, occurrence)
    return new.join(li)

buildpath = (os.popen('pwd').read()).strip('\n')
buildname = os.path.basename(buildpath)

try:  # madagascar version
    Import('env root pkgdir libdir bindir')
    # replace the last occurrence
    thispath = rreplace(buildpath,'build/','',1)
    thisname = rreplace(buildname,'build/','',1)
    testflag = 'no'
    docflag  = 'no'
except: # autonomous version
    # import compiler variables, testflag
    Import('vars', 'testflag', 'docflag')
    thispath = buildpath
    thisname = buildname
    root = None

#print 'thispath = '+thispath
#print 'thisname = '+thisname

def getlist(filename):
    alist=[]
    pathfile=os.path.join(thispath,filename)
    if os.path.exists(pathfile):
        f = open(pathfile,'r')
        alist = (f.read().strip('\n')).split(':')
        f.close()
    return alist

# extract package dependencies from hclasspath file
deplist=getlist('hclasspath')

#print ['deplist = ']+deplist

# extract nonstandard external header dependencies from hincpath file
extincs=getlist('hincpath')

# extract nonstandard external library dependencies from hlibpath file
extlibs=getlist('hlibpath')

#print ['extlibs = ']+extlibs

# extract nonstandard source search path from hsrcpath file, if it exists,
# else set up standard search in src and/or lib if either/both exist

srclist=getlist('hsrcpath')
if not srclist:
    if os.path.exists(os.path.join(thispath,'src')):
        srclist.append('src')
    if os.path.exists(os.path.join(thispath,'lib')):
        srclist.append('lib')

#print ['srclist = ']+srclist

cpplist = []
libdirlist = []
liblist = []

# start include list with this package
if os.path.exists(thispath+'/include'):
    cpplist.append(thispath+'/include')

# start library list with this package
if os.path.exists(thispath+'/lib'):
    libdirlist.append(buildpath+'/lib')
    liblist.append('lib'+thisname+'.a')

# add other standard packages - headers in "include", library in "lib" with title
# = lib[basename of package].a 
for n in deplist:
# if root undefined, then not in madagascar environment
    # Madagascar branch
    if root:
        testpath=os.path.abspath(os.path.expandvars(os.path.join(thispath,n)))
    else:
        testpath=os.path.abspath(os.path.expandvars(n))
    testincl=testpath+'/include'
    if os.path.exists(testincl):
        cpplist.append(testincl)
    testbuildpath=os.path.abspath(os.path.expandvars(os.path.join(buildpath,n)))
    testlibdir=testpath+'/lib'
    testlib='lib'+os.path.basename(testpath)+'.a'
    #    print 'testing for '+testlibdir
    # only test for lib dir - lib may not yet be built! 
    if os.path.exists(testlibdir):
        liblist.append(testlib)
        # Madagascar branch
    if root:
        libdirlist.append(testbuildpath + '/lib')
        # Standalone branch
    else:
        libdirlist.append(testpath + '/lib')

# add other possibly nonstandard sources of headers
# it is ALWAYS PRESUMED that header files live in final leaves
# of directory trees titled "include", so only path to parent dir
# should be included
for n in extincs:
    testpath=os.path.abspath(os.path.expandvars(n))
    testincl=testpath+'/include'
    if os.path.exists(testincl):
        cpplist.append(testincl)

# add other possibly nonstandard sources of libraries
# it CANNOT BE PRESUMED that library files live in any particular
# place, so full pathnames to external libraries must be given
for n in extlibs:
    libpath=os.path.abspath(os.path.expandvars(n))
    liblist.append(os.path.basename(libpath))
    libdirlist.append(os.path.dirname(libpath))

# finish with -lm - always!
liblist.append('-lm')

# determine base name of library - same as package name
libname = thisname

# test for lib - build library
if os.path.exists(thispath+'/lib'):
    # export environment and basename
    if root:
        Export('env root pkgdir libdir libname cpplist srclist')
    else:
        Export('vars libname cpplist srclist')
    # build in lib
    SConscript('lib/SConscript')

#test for main - build executables 
if os.path.exists(thispath+'/main'):
    if root:
        Export('env root pkgdir bindir cpplist liblist libname libdirlist')
    else:
        Export('vars cpplist liblist libname libdirlist')
    SConscript('main/SConscript')

#test for test flag, test source directories - build executables, run tests 
if testflag == 'yes':
   if os.path.exists('testsrc'):
       Export('vars', 'cpplist','liblist','libdirlist')
       SConscript('testsrc/SConscript')
   if os.path.exists('test'):
       Export('vars', 'cpplist','liblist','libdirlist')
       SConscript('test/SConscript')

#test for doc flag, attempt to build docs if it exists
if docflag == 'yes':
   if os.path.exists('doc'):
       os.system('cd doc; doxygen')

