#!/bin/env bash
####################################################################
###
### Restarts and ensemble member based on the type of error
###
####################################################################
# set -x
usage()
{
cat << EOF
OPTIONS:
   -h      Show this message
   -d      enable debug mode (-> log file)

EOF
}


log()
{
    eval $@
    echo $@
}


debug=0
while getopts “hd” OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
	 d)
	     debug=1
	     shift
	     ;;
         ?)
             usage
             exit
             ;;
     esac
done


HERE=${PWD}

oldRun=$1
run=${HERE}/`echo ${oldRun} | sed "s/_.*//"`_running
log mv ${oldRun} ${run} 2>/dev/null

subDir=${run}/trash/
log sub=`ls ${subDir}/tmp*.sub`
log spnLenOrg=`grep "export noy" ${sub} | cut -d= -f2`
log orbvOrg=`grep "export orbv" ${sub} | cut -d= -f2`
log orbyOrg=`grep "export orby" ${sub} | cut -d= -f2`       ## Modified for orbv
log dOrby=`grep "export dOrby" ${sub} | cut -d= -f2`
log loveYearStep=`grep "export loveYearStep" ${sub} | cut -d= -f2`
log loveStartYear=$((`grep "export ic=" ${sub} | cut -d= -f2 | sed 's/.*ic[0]*\([0-9]*\).*/\1/'` + 0))


# ###   1. Is there any scratch_* directory?
# ##       If so, look in love/RUN/V1.3/expdir/run/repo
cd ${run} || exit 1
# ls -d scratch* 1>/dev/null 2>&1

## If there is any scratch directory
# if [[ $? == '0' ]]; then
#     ## Take the most recent scratch directory (there should be one anyway!)
#     scrDir=`ls -d scratch* | tail -1`
#     cd ${scrDir}/love/RUN/V1.3/expdir/run/repo && (

#     ## Move all good ic* s to main/loveclim/ic
#     log mv `\du -s ic* | awk '$1>10000' | cut -f2` ${run}/main/loveclim/ic
#     )

#     cd ${run}
#     log rm -rf ${scrDir}
# fi

rm -rf scratch*

## Find the last successful LOVECLIM year from ic* directory name
cd ${run}/main/loveclim/ic
for d in `ls -d ic* | grep -v .tar.gz`; do
    tar -czf ${d}.tar.gz ${d}
    rm -r ${d}
done
log lastLoveYear=`ls | tail -1 | sed 's/.*ic[0]*\([0-9]*\).*/\1/'`


###  2. If there is no IC in main/loveclim/ic, look for spinup
if [[ -n ${lastLoveYear} ]]; then
    log newSub=${sub}.${lastLoveYear}
    log cp ${sub} ${newSub}
elif [[ ! -n ${lastLoveYear} ]] && [[ -e ${run}/spinup/ic/spinupICs.tar.gz ]]; then
    log lastLoveYear=`tar -tzvf ${run}/spinup/ic/spinupICs.tar.gz | grep inatdyn | tail -1 | sed 's/.*inatdyn[0]*\([0-9]*\).*/\1/'`
    log newSub=${sub}.${lastLoveYear}
    log cp ${sub} ${newSub}
elif [[ ! -e ${run}/spinup/ic/spinupICs.tar.gz ]]; then
    ## Start from scratch
    cd ${HERE}
    run=`echo ${run} | sed "s/_running//"`
    mv -v ${run}_running ${run}
    rm -r ${run}/spinup ${run}/main
    sub=`ls ${run}/trash/tmp*.sub`
    qsub ${sub}
    exit 0
fi


###  Modify tmpinc.sub with new values
# newSub=${run}/trash/tmpinc.sub.${lastLoveYear}



## Equivalent orbital year of the last LOVECLIM restart file
if [[ $((lastLoveYear-loveStartYear)) -gt ${spnLenOrg} ]]; then
    log spn=0
    # log eqLoveOrbYear=$((lastLoveYear-spnLenOrg*(1-orbvOrg)+orbyOrg))
    # log eqLoveOrbYear=$(( (lastLoveYear-spnLenOrg-100)*5+(spnLenOrg+100)+orbyOrg))
    # log eqLoveOrbYear=$(( (lastLoveYear-spnLenOrg)+orbyOrg))
    ##                             <      transient run without first 100 years          > < spinup + transient first 100 years >
    log eqLoveOrbYear=$(( orbyOrg + (lastLoveYear-loveStartYear - (spnLenOrg)) * dOrby/loveYearStep + (spnLenOrg) ))

    ## If lastLoveYear > spnLenOrg, then look for last GSM year
    cd ${run}/main/GSM || exit 1

    ## Get GSM orbital year
    if [[ `ls idat123.*` ]]; then 
	log gsmOrbYear=`tail -1 idat123.* | awk '{print 1000*$1}'`

    ## If no idat123 file present, exit
    else
	cat <<EOF
## No GSM idat123 file available!
## Run gsmOnly to generate restart files.
##
## GSM orbital year needed: ${eqLoveOrbYear}
EOF

	exit 1
    fi

    if [[ ${eqLoveOrbYear} -ne ${gsmOrbYear} ]]; then
	echo "loveclim: ${eqLoveOrbYear} not equal GSM:${gsmOrbYear}!"
	exit 1
    fi

    log iter=`echo "( ${lastLoveYear}-${loveStartYear}-${spnLenOrg} ) / ${loveYearStep} + 1" | bc`

    sed -i "s/export\ berg=.*/export\ berg=berg`printf '%07d' ${eqLoveOrbYear}`.nc/" ${newSub}
    sed -i "s/export\ icemask=.*/export\ icemask=icemask`printf '%07d' ${eqLoveOrbYear}`.nc/" ${newSub}
elif [[ $((lastLoveYear-loveStartYear)) -eq ${spnLenOrg} ]]; then
    log spn=0
    log eqLoveOrbYear=$(( (lastLoveYear-loveStartYear)*orbvOrg+orbyOrg ))
    log iter=1

    log cd ${run}/spinup/ic
    log tar -xzf spinupICs.tar.gz ic`printf %06d ${lastLoveYear}`_360
    log tar -czf ic`printf %06d ${lastLoveYear}`_360.tar.gz ic`printf %06d ${lastLoveYear}`_360
    log mv ic`printf %06d ${lastLoveYear}`_360.tar.gz ${run}/main/loveclim/ic

    log cd ${run}/spinup/nc
    log cp berg${orbyOrg}.nc ${run}/main/loveclim/nc/berg`printf '%07d' ${eqLoveOrbYear}`.nc
    log cp icemask${orbyOrg}.nc ${run}/main/loveclim/nc/icemask`printf '%07d' ${eqLoveOrbYear}`.nc

    sed -i "s/export\ berg=.*/export\ berg=berg`printf '%07d' ${eqLoveOrbYear}`.nc/" ${newSub}
    sed -i "s/export\ icemask=.*/export\ icemask=icemask`printf '%07d' ${eqLoveOrbYear}`.nc/" ${newSub}
else
    log spn=1
    log eqLoveOrbYear=$(( (lastLoveYear-loveStartYear)*orbvOrg+orbyOrg ))
    log iter=`echo " (${lastLoveYear}-${loveStartYear}) / 100 + 1" | bc`

    log cd ${run}/spinup/nc
    log cp berg${orbyOrg}.nc ${run}/main/loveclim/nc/berg${orbyOrg}.nc
    log cp icemask${orbyOrg}.nc ${run}/main/loveclim/nc/icemask${orbyOrg}.nc

    sed -i "s/export\ berg=.*/export\ berg=berg${orbyOrg}.nc/" ${newSub}
    sed -i "s/export\ icemask=.*/export\ icemask=icemask${orbyOrg}.nc/" ${newSub}
fi


sed -i "s/export\ iter=.*/export\ iter=${iter}/" ${newSub}
sed -i "s/export\ loveYear=.*/export\ loveYear=$((lastLoveYear+1))/" ${newSub}
sed -i "s/export\ cnt=.*/export\ cnt=1/" ${newSub}
sed -i "s/export\ spn=.*/export\ spn=${spn}/" ${newSub}
sed -i "s/export\ orby=.*/export\ orby=${eqLoveOrbYear}/" ${newSub}
sed -i "s/export\ ic=.*/export\ ic=ic`printf %06d ${lastLoveYear}`_360/" ${newSub}




# sed -i "4s/[0-9]\{8\}-[0-9]\{6\}\.log$/`date +%Y%m%d-%H%M%S`\.log/" ${newSub}
# sed -i "s,FAILEDRUN,${scratch}," ${newSub}




# sed -i "s/NODE/cl\.\*/" ${newSub}






# # steps=${subDir}/steps.log
# # log=`ls ${run}/trash/*.log | tail -1`

# lastGood=`ls | tail -1 | cut -c3-8 | sed 's/^0*//'`
# if [[ ! -n ${lastGood} ]]; then lastGood=0; fi
# loveYear=`echo "${lastGood} + 1" | bc`


# cd ${HERE}
# spnLenOrg=`grep "export noy" ${sub} | cut -d= -f2`
# orbvOrg=`grep "export orbv" ${sub} | cut -d= -f2`
# orbyOrg=`grep "export orby" ${sub} | cut -d= -f2`       ## Modified for orbv
# loveYearStep=`grep "export loveYearStep" ${sub} | cut -d= -f2`

# ## Change tmpInc.sub to prepare for continuation
# newSub=${sub}.new
# cp -v ${sub} ${newSub}

# if [[ `echo "${lastGood} >= ${spnLenOrg}" | bc` == '1' ]]; then
#     ## No more spin-up, continue the Main run

#     ## Grab step.log
#     lastModel=`tail -1 ${steps} | awk '{print $1}'`
    
#     ## Valid if last model is NOT LOVECLIM
#     iter=`echo "(${lastGood} - ${spnLenOrg}) / ${loveYearStep} + 1" | bc`
    
#     if [[ ${orbvOrg} == '0' ]]; then
# 	spnLenOrg=0
#     fi
#     orbyNew=`echo "${orbyOrg} + ${spnLenOrg} + (${iter}-1) * ${loveYearStep}" | bc`

#     # if [[ ${lastModel} == 'Loveclim' ]]; then
#     # 	iter=$((iter - 1))
#     # 	orbyNew=$((orbyNew - loveYearStep))
#     # fi
    
#     sed -i "s/export\ lastModel=.*/export\ lastModel=${lastModel}/" ${newSub}
#     sed -i "s/export\ spn=.*/export\ spn=0/" ${newSub}
    
# else
#     ## Continue with spin-up
#     if [[ ${orbvOrg} == '1' ]]; then
# 	orbyNew=`echo "${orbyOrg} + ${lastGood}" | bc`
#     else
# 	orbyNew=${orbyOrg}
#     fi
    
#     iter=`echo "${lastGood}/100+1" | bc`
# fi

# sed -i "4s/[0-9]\{8\}-[0-9]\{6\}\.log$/`date +%Y%m%d-%H%M%S`\.log/" ${newSub}
# sed -i "s,FAILEDRUN,${scratch}," ${newSub}
# sed -i "s/export\ cnt=.*/export\ cnt=1/" ${newSub}
# sed -i "s/export\ iter=.*/export\ iter=${iter}/" ${newSub}
# sed -i "s/export\ loveYear=.*/export\ loveYear=${loveYear}/" ${newSub}
# sed -i "s/export\ orby=.*/export\ orby=${orbyNew}/" ${newSub}
# sed -i "s/NODE/cl\.\*/" ${newSub}

# qsubd ${newSub}
set -x
if [[ -e ${HERE}/nodes ]]; then
    subNodes=`grep -v "#" ${HERE}/nodes | tr '\n' '|' | sed 's/|$//'`
    qsub -l h="(${subNodes})" ${newSub}
else
    qsub ${newSub}
fi



##########################################################
##
## eqLoveOrbYear : equivalent LOVECLIM orbital year
## 
