#!/bin/bash

#    ./reb $type $ym $SIM $SIMUDIR

ym=$1
SIMUDIR=$2
SIM=$(basename "$SIMUDIR"); shift 2
types="$*"
PUT="mv"
rebuild=/gpfswork/rech/groupe/rgroupe027/LMDZ20191008.trunkOR3013/modipsl/bin/rebuild
local=$(pwd)

. lmdz_env.sh

echo "type $type"
echo "ym $ym"
echo "SIM $SIM"
echo "SIMUDIR $SIMUDIR"

for type in $types; do
  job=$SIM$type

  cat <<eod >| "$job"
#!/bin/bash
## Headers managed by sed
#@JZ#JeanZay
#@JZ#SBATCH --job-name=Seq              # nom du job
#@JZ#SBATCH --nodes=1                   # nombre de noeuds
#@JZ#SBATCH --ntasks-per-node=1         # nombre de taches MPI par noeud
#@JZ#SBATCH --time=03:00:00             # temps d execution maximum demande (HH:MM:SS)
#@JZ#SBATCH --output=post${type}%j.out  # nom du fichier de sortie
#@JZ#SBATCH --error=post${type}%j.out   # nom du fichier d'erreur (ici en commun avec la sortie)
#@SP#Spirit
#@SP#SBATCH --job-name=Seq
#@SP#SBATCH --nodes=1
#@SP#SBATCH --ntasks-per-node=1
#@SP#SBATCH --time=03:00:00
#@SP#SBATCH --output=post${type}%j.out
#@SP#SBATCH --error=post${type}%j.out
#@ADS#Adastra
#@ADS#SBATCH --job-name=Seq
#@ADS#SBATCH --nodes=1
#@ADS#SBATCH --ntasks-per-node=1
#@ADS#SBATCH --time=03:00:00
#@ADS#SBATCH --output=post${type}%j.out
#@ADS#SBATCH --error=post${type}%j.out

# on se place dans le repertoire de soumission
cd $local
pwd

. lmdz_env.sh

ulimit -s unlimited
if [[ -f ${type}_0000.nc ]]; then
  $RUNBASHCMD $rebuild -o ${type}.$ym.nc ${type}_[0-9][0-9][0-9][0-9].nc
else
  echo "${type}_0000.nc absent"
fi
if [[ -f $type.$ym.nc ]]; then
   ${PUT} $type.$ym.nc ${SIMUDIR}/$type.$ym.nc
   rm -f ${type}_[0-9][0-9][0-9][0-9].nc
else
   echo "La reconstruction de $type.$ym.nc a echoué"
fi
eod

  #echo "Submitting the rebuild job $job using <$SUBMITCMD \"$job\">"
  #$SUBMITCMD "$job"
  echo "Submitting the rebuild job $job using <submitcmd \"$job\">"
  submitcmd "$job"
done
