#!/bin/bash

function log()
{
    echo $*
    $*
}

function full_dir()
{
    (cd -P $1 ; pwd)
}

#--------------- Generate kernels, invoked by : './make_python kernels' ---------------

function update()
{
 diff $2 $1 || log cp -pr $1 $2
}

function cmd_kernels() # this function is invoked by : './make_python kernels'
{
    cd $KERNELS
    ./codegen hexagonal unstructured

    cd $KERNELS/src/hexagonal
    for x in *.k90 ; do
	update "$x" "$DYNAMICO_ROOT/src/kernels_hex/$x"
    done

    cd $KERNELS/src/unstructured
    for x in *.k90 ; do
	update "$x" "$DYNAMICO_ROOT/src/kernels_unst/$x"
    done

# make sure to recompile dynamics
    cd $DYNAMICO_ROOT
    touch src/dynamics/*.F90 src/diagnostics/*.F90 src/transport/*.F90 src/unstructured/*.F90}
}

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

function make_so()
{
    ARLIB=$1
    SOLIB=$2
    ls -l $ARLIB
    ls -l $SOLIB
    if [[ $ARLIB -nt $SOLIB ]]; then
        echo $ARLIB is newer than $SOLIB
        log $LINK $SOFLAGS $WHOLE_ARCHIVE $ARLIB $NO_WHOLE_ARCHIVE $3 -o $SOLIB
        $LDD $SOLIB
    fi
}


function cmd_()
{
    make_so $XIOS_ROOTDIR/lib/libxios.a $LIBDIR/libxios.so "$NETCDF_LDFLAGS"
    make_so $LIBDIR/libicosa.a $LIBDIR/libicosa.so "-L$LIBDIR -lxios"

    # Cythonize Python modules
    cd $DYNAMICO_ROOT/Python/src
    CYTHONFLAGS="$SOFLAGS $LDFLAGS -L$LIBDIR -licosa"
    LDSHARED="$LINK" CFLAGS="-fno-strict-aliasing -O2" LDFLAGS="$CYTHONFLAGS" log python setup.py build_ext --inplace
    cp -fp *.so $DYNAMICO_ROOT/Python/dynamico
    cd ..
#    python -c 'import dynamico ; help(dynamico)'
}

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

DYNAMICO_ROOT=$PWD
LIBDIR=$DYNAMICO_ROOT/lib
KERNELS=$DYNAMICO_ROOT/Python

. arch.env
. arch.path

echo "Selected architecture : $CURRENT_ARCH"

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

. Python/env/${CURRENT_ARCH}.env

cmd_$1
