#!/bin/bash

make_scons() {
libname="Proc_"$(basename $(pwd))
sources=$(for i in $*; do printf $i | sed "s/^/'/1;s/$/',/1" | tr '\n' ' '; done | sed 's/,$//1')
echo "import os
Import('env')
lenv=env.Clone()
procobj = lenv.SharedObject([${sources}])
proclib = lenv.SharedLibrary('${libname}',[])
Depends(proclib,procobj)
with open('${libname}.rsp',\"w\") as f:
    for o in procobj:
        f.write ('%s\n' %os.path.abspath(str(o)).replace('\\\\','/'))
lenv.Append(LINKFLAGS=['@%s' % os.path.abspath('${libname}.rsp')])
lenv.Install('\${libdir}',proclib)
lenv.Alias('install',['\${libdir}'])" > SConscript
}

procdir="Process/Amegic/*";
test -z "$1" || procdir=$1;

basedir=$PWD;
if test -z "$2"; then
echo "import os
vars = Variables()
vars.Add(PathVariable('libdir','lib path',os.getcwd()+'/Process/Amegic/lib',PathVariable.PathIsDirCreate))
vars.Add('CC','The C++ Compiler','@CC@')
vars.Add('CXX','The C++ Compiler','@CXX@')
vars.Add('CFLAGS','The C++ Flags',['@CFLAGS@'.split(" "),'-g0','-O2'])
vars.Add('CXXFLAGS','The C++ Flags',['@AM_CXXFLAGS@'.split(" "),'@CXXFLAGS@'.split(" "),'-g0','-O2'])
vars.Add(PathVariable('incdir','include path','@INCLUDEDIR@',PathVariable.PathIsDir))
env = Environment(variables=vars,CPPPATH=['\${incdir}'],ENV=os.environ)
if env['PLATFORM']=='darwin':
   env.Append( LINKFLAGS='-Wl,-undefined -Wl,dynamic_lookup' )
" > SConstruct;
fi;
test "$procdir" = "x" && exit 0;
printf "Processing ("$procdir": "$(echo $procdir/?_?__* $procdir/fsr* | wc -w)") ";
for i in $procdir/?_?__* $procdir/fsr*; do
  test -d $i || continue;
  cd $i; printf ".";
  make_scons *.C
  subdir=$(printf $PWD | sed 's|'${basedir}'||1;s|/||1')
  if test $2 -eq 1; then
    echo "SConscript('${subdir}/SConscript',exports='env')"  >> $basedir/SConstruct;
  fi
  cd $basedir;
done;
if test $2 -eq 2 && test -d $procdir; then
  cd $procdir; printf ".";
  make_scons $(find . -name \*.C | grep -v fsrchannels)
  subdir=$(printf $PWD | sed 's|'${basedir}'||1;s|/||1')
  echo "SConscript('${subdir}/SConscript',exports='env')"  >> $basedir/SConstruct;
  for i in fsr*; do
    if test -d $i; then
      cd $i; printf ".";
      subdir=$(printf $PWD | sed 's|'${basedir}'||1;s|/||1')
      echo "SConscript('${subdir}/SConscript',exports='env')"  >> $basedir/SConstruct;
      cd ..
    fi
  done
  cd $basedir;
fi
echo " done";
