#!/bin/bash

function build_dynamico_()
{
    NAME=$1 ; shift
    LOGFILE=$1 ; shift
    echo "# command used to build DYNAMICO ($NAME) :" >> logs/build.sh
    echo "./make_icosa $*" >> logs/build.sh

    cd $ROOT/build_$NAME
    echo "In $PWD : building DYNAMICO with options $*"
    echo "Watch logfile $LOGFILE"

    ./make_icosa $* > $LOGFILE 2>&1
}
 
function build_dynamico()
{
    NAME=$1 ; shift
    LOGFILE=$ROOT/logs/dynamico_${NAME}.log
    BUILD=$ROOT/build_$NAME
    build_dynamico_ $NAME $LOGFILE -arch $arch -job $job $* || ( tail $LOGFILE ; exit 1 )
    cp -pr $BUILD/bin/icosa_gcm.exe  $ROOT/bin/icosa_$NAME.exe
}

function build_xios()
{
    LOGFILE=$1 ; shift
    echo '# command used to build XIOS :' >> logs/build.sh
    echo "./make_xios $*" >> logs/build.sh
    
    cd -P $ROOT/XIOS
    echo "In $PWD : Building XIOS"
    echo "Watch logfile $LOGFILE"
    echo "./make_xios $*"
    ./make_xios $* > $LOGFILE 2>&1
}

function main()
{
    rm -f tmp/build.sh
    LOGFILE=$ROOT/logs/build_xios.log
    build_xios $LOGFILE --arch $arch_XIOS $other_XIOS --job $job || ( tail $LOGFILE ; exit 1 )

    cd $ROOT
    # compile all variants in parallel
#    build_dynamico serial -parallel none $FULL &
    build_dynamico mpi -parallel mpi -with_xios $other $FULL &
    build_dynamico mpi_omp -parallel mpi_omp -with_xios $other $FULL &
    wait
    # check success
#    ls bin/icosa_serial.exe || exit 1
    ls bin/icosa_mpi.exe || exit 1
    ls bin/icosa_mpi_omp.exe || exit 1
}

FULL=$1
source current_args
rm -rf bin logs
mkdir bin logs
( main ) || ( echo ; echo "***************** Build FAILED ******************" )

echo
echo "You may now run create_runs.sh"
