#!/bin/bash
#SBATCH --job-name=soc2 
#SBATCH --account=rozanov
#SBATCH --nodes=1  
#SBATCH --time=10:00:00 
#SBATCH --ntasks=60 
#SBATCH --ntasks-per-core=1 
#SBATCH --mem-per-cpu=8000
#SBATCH --output=/net/storage/scratch/home/rozanov/orava/SOCOL_ETH_ocean/run/slurm_run_socol_%j.out 
#SBATCH --error=/net/storage/scratch/home/rozanov/orava/SOCOL_ETH_ocean/run/slurm_run_socol_%j.txt 


ulimit -s unlimited

EXPNO=100001
EXPERIMENTEYEAR=1850

set +e

srun /net/storage/scratch/home/rozanov/orava/SOCOL_ETH_ocean/bin/echam5

exit_status="$?"

set -e

flag_further_integration=false

case $exit_status in
   0)   # echam checkpoint (there will be further integrations)
        flag_further_integration=true
   ;;
   127) # echam normal end of experiment
      : # do nothing
   ;;
   *)   # echam error
      echo "ERROR: model run stopped with return value ${exit_status}."
      exit 1
   ;;
esac

#----------------------------------------------------------------
#-- Parse date and time infos in global metadata of a netcdf file
#   and convert it into a proper datetime
function rerun_file_datetime_metadata_to_datetime()

{

   local rerun_file="$1"
   local str_date="$2"
   local str_time="$3"
   local output_var="$4"
   local parsed_date
   local parsed_time
   local datetime

   parsed_date=`ncdump -h ${rerun_file} | \
                  sed -n -e "s/^.*:${str_date} = \([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\).*$/\1/p"`

   if [ -z "$parsed_date" ] ; then
      err_msg "Could not parse $str_date info from ${rerun_file}!"
      educated_exit
   fi

   parsed_date="${parsed_date:0:4}-${parsed_date:4:2}-${parsed_date:6:2}"

   parsed_time=`ncdump -h ${rerun_file} | sed -n -e "s/^.*:${str_time} = \([0-9][0-9]*\).*$/\1/p"`
   if [ -z "$parsed_time" ] ; then
      echo "Could not parse $str_time info from ${rerun_file}!"
      educated_exit
   fi

   parsed_time=`printf '%06d' $parsed_time`

   parsed_time="${parsed_time:0:2}:${parsed_time:2:2}:${parsed_time:4:2}"

   set +e
   trap '' ERR # disable error trap
   datetime=`date --utc --date "$parsed_date $parsed_time" 2> /dev/null`
   trap traceback ERR # re-enable error trap
   set -e

   if [ ! -z "$datetime" ] ; then
      #-- datetime is defined
      eval "$output_var=\"$parsed_date\""
   else
      #-- datetime is undefined because datetime_nml was invalid
      invalid_datetime $datetime_nml $output_var
      educated_exit
   fi

}


rerun_file_datetime_metadata_to_datetime "rerun_${EXPNO}_echam" "vdate" "vtime" "prev_ending_datetime"
echo  $prev_ending_datetime???? 

YY1=${prev_ending_datetime:0:4}



# Save restart files:
# a) ECHAM5:
cp -f rerun_${EXPNO}_echam ${EXPNO}_rerun_${YY1}12_echam.nc
gzip -f ${EXPNO}_rerun_${YY1}12_echam.nc

# b) MEZON:
cp -f rerun_${EXPNO}_tracer ${EXPNO}_rerun_${YY1}12_chem1.nc
gzip -f ${EXPNO}_rerun_${YY1}12_chem1.nc

if [ ${YY1} -ge ${EXPERIMENTEYEAR} ]; then
   exit
else
   sbatch /net/storage/scratch/home/rozanov/orava/SOCOL_ETH_ocean/run/slurm 
fi

