#!/bin/bash

function log()
{
    echo $*
    $*
}

#----------- Extract DySL from Fortran, invoked by : './make_DySL extract' ------------

function cmd_extract()
{
    XT=$KERNELS/kernels_extracted.jin
    rm -f $XT
    touch $XT
    cd $DYNAMICO_ROOT/src
    for F90 in */*.F90 ; do
	sed -n '/BEGIN_DYSL/,/END_DYSL/{//b;p}' $F90 >> $XT
    done
    cd $DYNAMICO_ROOT
}

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

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

function update_kernels()
{
    cd $KERNELS/$1
    for x in *.k90 ; do
	update "$x" "$DYNAMICO_ROOT/src/$2/$x"
    done
}

function cmd_() 
{
    cmd_clean
    cmd_extract
    cd $KERNELS
    ./codegen hexagonal hex_master unstructured
    update_kernels hexagonal kernels_hex
    update_kernels hex_master kernels_hex_master
    update_kernels unstructured kernels_unst
# make sure that ./rebuild recompiles dynamics
    cd $DYNAMICO_ROOT
#    touch src/dynamics/*.F90 src/diagnostics/*.F90 src/transport/*.F90 src/unstructured/*.F90
}

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

DYNAMICO_ROOT=$PWD
KERNELS=$DYNAMICO_ROOT/DySL

. 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 ..
time cmd_$1
