#!/usr/bin/env python
import os, time, sys, glob

# for the following two, AADIR should be in pythonpath
from util.aafabricate import *
from setup import *

where_geant_at = '/pbs/throng/km3net/share/geant/geant4.10.05_build'

incgeant = "-I/"+where_geant_at+'/include/Geant4'

libgeant = '-Wl,-rpath,'+where_geant_at+'/lib64 -L'+where_geant_at+'/lib64 -lG4Tree -lG4FR -lG4GMocren -lG4visHepRep -lG4RayTracer -lG4VRML -lG4vis_management -lG4modeling -lG4interfaces -lG4persistency -lG4analysis -lG4error_propagation -lG4readout -lG4physicslists -lG4run -lG4event -lG4tracking -lG4parmodels -lG4processes -lG4digits_hits -lG4track -lG4particles -lG4geometry -lG4materials -lG4graphics_reps -lG4intercoms -lG4global -lG4clhep'

sources = [ x for x in glob.glob("*.cc") if not ".dict." in x ]


def base( s ):
    return s.rsplit('.',1)[0]

def write_dictionary( s ) :    
    dict_cc_file = base(s)+'.dict.cc'
    linkdef      = base(s)+'.linkdef.h'
    s            = s.replace(".cc",".hh")
    run('rootcling -f {dict_cc_file} {incgeant} {rootcintopt} {incaa} {incroot} {incjpp} {s} {linkdef}')


def build_dictionary( s ):
    compile( base(s)+'.dict.cc' )

def compile( s ) :
    print (" ===== compiling ", s , incgeant)
    obj = base(s)+'.o'

    # tell gcc we really want to build an obj file
    if s.endswith('h') : xopt = "-x c++" 
    else               : xopt = ""
    
    run('g++  {gccopt} -c -o {obj} {incgeant} {incaa} {incroot} {incjpp} {xopt} {s}')


def make_library( sources ):
    objs = " ".join( [ base(s)+'.o ' for s in sources] )
    res = run('g++ {gccopt} -shared {objs} {libgeant} {libroot} {libjpp} -o ../lib/libsim.so')

    #copy all pcm files to the lib
    print ('copying pcm')
    os.system('cp `find . -name "*.pcm"` ../lib/')


def make_exe( s ):
    print (" ===== compiling ", s)    
    exe = base(s)
    run('g++  {gccopt} -o {exe} {incgeant} {incaa} {incroot} {incjpp} {libjpp} {libroot} {libaa} {s}')

def build():
  
    for s in sources : compile(s)
    after()

    write_dictionary( "Sim.hh" )
    after()
    
    build_dictionary( "Sim.hh" )
    after()

    make_library( sources + ["Sim.dict.o"] )


def clean():
    autoclean()

main(parallel_ok=False, jobs=10)