# Build the PIK machine learning interface.
# It sends data from the coupler to libtorch.

# However, we cannot compile this interface with Intel compiler.
# Currently (Dec 2021) they provide two precompiled distributions of
# libtorch: One called CXX11 ABI interface. However, that is built
# against a math library libm.so which is too new for the PIK HLRS2015
# cluster. The other is denominated pre-CXX11 , but in reality is
# post-post-CXX11 because it requires lots of CXX14 and apparently
# also some CXX17 features.  The Intel compiler does not provide
# sufficient support for it, and/or the libtorch build process is not
# prepared to handle the Intel compiler suite.  However, on the PIK
# cluster we can build applications on this distribution with
# gcc-7.3.0 which is available packaged as environment module.

 
set lib_name = "lib_pik_ml"

# make sure that gcc-7.3.0 is used for this compilation
# -> to be set in the mkmf template
#setenv CC /p/system/packages/compiler/gnu/7.3.0/bin/gcc
#setenv CXX /p/system/packages/compiler/gnu/7.3.0/bin/g++

set pathnames = $executable:h:h/$lib_name/pik_ml_command-$$

set srcList = ( $pathnames )

mkdir -p $executable:h:h/$lib_name

set cppfiles = " \
$code_dir/pik_ml/pik_ml_interface.cpp \
`find $code_dir/pik_ml/online-gan/src -name '*.cpp' -print | fgrep -v main.cpp`"

# settings taken from cmake output
set libtorchdefs = "-DUSE_C10D_GLOO -DUSE_DISTRIBUTED -DUSE_RPC -DUSE_TENSORPIPE -D_GLIBCXX_USE_CXX11_ABI=0 -std=gnu++14"
echo "" > $pathnames
foreach i ( $cppfiles )
    echo '$(GXX)' $libtorchdefs '$(CPPDEFS) $(CPPFLAGS) $(GXXFLAGS) $(FPPFLAGS) $(LIBTORCHINCLUDE) -c ' $i >> $pathnames
end

cd $executable:h:h/$lib_name
$mkmf_lib -p $lib_name.a -c "$cppDefs"  -o "-I$executable:h:h/lib_FMS -I$code_dir/pik_ml/online-gan/include" $srcList $lib_include_dirs
rm -f $pathnames
make

if( $status ) then
    echo "Make failed to create $lib_name.a"
    exit 1
endif

#set srcList = "$srcList pik_ml/pik_ml_interface.cpp"                                                         
set includes = "$includes -I$executable:h:h/lib_pik_ml $LIBTORCHINCLUDE"
set pik_ml_libs = "-L$executable:h:h/lib_pik_ml -l_pik_ml $LIBTORCHLIBS"
