#!/bin/bash
# How to use this script :
# 1    Create a directory EXP for your experiment ; ALL commands below must be run from EXP
# 2    Create a directory STORE to store the outputs of your experiment ; run "ln -s STORE storedir"
# 3    run "BASE/example.sh init" where BASE is the directory containing this script
# 4    (optional) Edit EXP/config.sh, EXP/run_icosa.def, EXP/*.xml
# 5    run "./example.sh create" (NB : ./example.sh, NOT ../example.sh)
# 6    run "./example.sh submit"

function fullpath() 
{ 
    echo "$(cd -P $1 ; pwd)"
}

function years()
{
    for ((i="$1";i<="$2";i++)) ; do
	echo $(printf 'year%02d' $i)
    done
}

function cmd_create()
{
    source ./config.sh
    env | grep YEARS
    STORE_ROOT=$( fullpath $PWD/storedir )
    YEARS=$(years 1 $NB_YEARS)
    for DIR in ce0l $YEARS ; do
	rm -rf $DIR $STORE_ROOT/$DIR
    done
    STORE0L="$STORE_ROOT/ce0l"
    $BASEDIR/prepare.sh ce0l ce0l "$STORE0L"
    $BASEDIR/prepare.sh first $STORE0L year01 "$STORE_ROOT/year01"
    PREV=year01
    for YEAR in $(years 2 $NB_YEARS) ; do
	$BASEDIR/prepare.sh next  $STORE0L "$STORE_ROOT/$PREV" $YEAR "$STORE_ROOT/$YEAR"
	PREV=$YEAR
    done
}

function submit_X64_CURIE()
{
    EXP=$1 ; shift
    CMD="ccc_msub $* $EXP/job.sh"
    MSG=$($CMD)
    echo "$CMD : $MSG"
    JOBID=$( echo "$MSG" | awk '{print $NF}' )
    DEP="-a $JOBID"
}

function cmd_submit()
{
    source ./config.sh
    DEP=""
    submit_$ARCH ce0l
    for YEAR in $(years 1 $NB_YEARS) ; do
	submit_$ARCH $YEAR $DEP
    done
}

function cmd_init()
{
    cp -fp $BASEDIR/*.sh $BASEDIR/*.xml $BASEDIR/*.def .
    cat > config.sh <<EOF
ARCH=X64_CURIE
BASEDIR=$BASEDIR
ESM_ROOT=$ESM_ROOT
NB_YEARS=10
NB_MPI_DYNAMICO=160
NB_MPI_XIOS=16
NB_MPI_CE0L=16
JOB_WALLTIME=7200
EOF
    ls -lrh
    cat config.sh
}

function cmd_()
{
echo
}

BASEDIR=$(dirname ${BASH_SOURCE[0]})
BASEDIR=$( fullpath $BASEDIR )
ESM_ROOT=$( fullpath $BASEDIR/../../ )
echo "Your command : $0 $*"
echo "Script base dir : $BASEDIR"
echo "Run from : $(fullpath $PWD)"
echo "Usage : $0 [init|create|submit]"
cmd_$1
