#!/bin/bash

function log()
{
    echo $*
    $*
}

function cmd_clean() # cleanup, invoked by : './make_python clean'
{
    rm -rf lib/*.so lib/dynamico
    cd $DYNAMICO_ROOT/Python/src
    rm -rf *.o *.so build/
}

function make_so()
{
    ARLIB=$1
    SOLIB=$2

    if [[ $ARLIB -nt $SOLIB ]]; then
        echo $ARLIB is newer than $SOLIB
	rm -f tmp.a
	cp $ARLIB tmp.a
	if [[ "$4" != "" ]] ; then ar vd tmp.a $4 ; fi
	if [[ "$5" != "" ]] ; then ar vr tmp.a $5 ; fi
        log $LINK $SOFLAGS $WHOLE_ARCHIVE tmp.a $NO_WHOLE_ARCHIVE $3 -o $SOLIB
	rm -f tmp.a
        $LDD $SOLIB
    fi
}

function check_python_modules()
{
    MISSING=""
    for module in $*; do
	echo "import $module"
	python -c "import $module" || MISSING="$MISSING $module"
    done
    if [[ "$MISSING" == "" ]] ; then
	echo "All required Python modules seem present."
    else
	echo "Missing/dysfunctional python modules : $MISSING"
	echo "Please fix your Python configuration"
	exit
    fi
}

function check_dynamico_modules()
{
    cd $DYNAMICO_ROOT
    for module in $*; do
	echo "import dynamico.$module"
	LD_PRELOAD=$PYTHON_PRELOAD python -c "import dynamico.$module"
    done
}

function cythonize()
{
    EXTRA=$1
    NUMPY=$(python -c 'import numpy as np ; print np.get_include()')
    CYTHONFLAGS="$SOFLAGS $LDFLAGS -L$LIBDIR $KERNELS_LDFLAGS $EXTRA"
    CC=mpicc LDSHARED="$LINK" CFLAGS="-fno-strict-aliasing -O2 -I$NUMPY $PARMETIS_CFLAGS" LDFLAGS="$CYTHONFLAGS" log python setup.py build_ext --inplace || exit
    rm -rf build *.c # temp files
}

#------------------ Default action , invoked by : './make_python' --------------------

function make_user()
{
    check_python_modules netCDF4 mpi4py
    # Cythonize Python modules
    cd $DYNAMICO_ROOT/Python/dynamico
    cythonize
    rm -rf build *.c # temp files
    cp -fpr $DYNAMICO_ROOT/Python/dynamico $DYNAMICO_ROOT/lib
    check_dynamico_modules partition meshes dyn time_step DCMIP
}

function make_dev()
{
    check_python_modules jinja2
    echo "XIOS_ROOTDIR : $XIOS_ROOTDIR"

    make_so $XIOS_ROOTDIR/lib/libxios.a $LIBDIR/libxios.so "$NETCDF_LDFLAGS -lstdc++"
    make_so $LIBDIR/libicosa.a $LIBDIR/libicosa.so "-L$LIBDIR -lxios $KERNELS_LDFLAGS" "physics_external_mod.o physics_mod.o timeloop_gcm_mod.o icosa_init_mod.o"

    cd $DYNAMICO_ROOT/Python/dev
    cythonize "-licosa"
    cp -fpr $DYNAMICO_ROOT/Python/dev $DYNAMICO_ROOT/lib/dynamico/
    check_dynamico_modules dev.cxios dev.unstructured
}

function cmd_()
{
    make_user
}

function cmd_dev()
{
    make_user
    make_dev
}


#------------------------- script starts here ------------------------

DYNAMICO_ROOT=$PWD
LIBDIR=$DYNAMICO_ROOT/lib

. arch.env
. arch.path

echo "Selected architecture : $CURRENT_ARCH"
if [[ "$CURRENT_ARCH" == "" ]] ; then echo "Current architecture undefined or unsupported" ; exit ; fi

cd arch
. arch-${CURRENT_ARCH}.dev
cd $DYNAMICO_ROOT

time cmd_$1
