#!/bin/bash 
source /etc/profile.d/modules.sh

#set -eu
#set -v

function usage {
  echo "Usage: $0 <recipe_template> -e=<EXPID> -str=<data_stream> -sd=YYYYMMDD -h=<forecast_horizon> "
  echo " "
  echo "  -e, --expid:       EXPID"
  echo "  [MANDATORY]"
  echo "  -r, --recipe:      Recipe template"
  echo "  [MANDATORY]"
  echo "  -h, --horizon:     Forecast horizon: 'subseasonal', 'seasonal', or 'decadal'"
  echo "  [MANDATORY]"
  echo "  -sd, --start_date: Start date (YYYYMMDD) of the forecast in YYYYMMDD"
  echo "                     format. If -str is hcst, any year can be used."
  echo "                     The default value is the current date."
  echo "  -cd, --code_dir:   Directory where the SUNSET code is stored."
  echo "                     The default value is the current working directory."
  echo " "
}


function parse_args {
  for i in "$@"; do
    case $i in
      -e=*|--expid=*)
        export expid=`echo $1 | sed -e 's/^[^=]*=//g'`
        shift
        ;;
      -r=*|--recipe=*)
	export recipe_template=`echo $1 | sed -e 's/^[^=]*=//g'`
	shift
	;;
      -sd=*|--start_date=*)
        export start_date=`echo $1 | sed -e 's/^[^=]*=//g'`
        shift
        ;;
      -cd=*|--code_dir=*)
        export code_dir=`echo $1 | sed -e 's/^[^=]*=//g'`
        shift
        ;;
      -h=*|--horizon=*)
        horizon="${i#*=}"
        shift # past argument=value
        ;;
      -h|--help)
        usage
        shift # past argument with no value
        ;;
      *)
      ;;
    esac
  done
  if [ -z "$start_date" ]; then
    start_date=$(date +%Y%m%d)
  fi
  if [ -z "$code_dir" ]; then
    code_dir=./
  fi
}

function get_startdate {
  for dl_date in ${start_date[@]}; do 
    if [[ $horizon == "subseasonal" ]];then
      week_day=$(date --date="$dl_date" +%a)
      # Check date and stream
      if [[ ${week_day} == Thu ]]; then
        sdate=($dl_date)
      else
        sdate=$(date --date "last Thursday" +%Y%m%d)
      fi
    else
      sdate=${dl_date:0:6}01
    fi
  done
}

function launch_auto {

  code_dir=${code_dir[@]}
  echo "*** Launching operational: ***"
  echo "[INFO] CURRENT TIME: $(date)"
  echo "[INFO] STARTDATE: ${sdate[@]}"
  echo "[INFO] Using EXPID: ${expid}"
  echo "[INFO] Running SUNSET launcher from ${code_dir}" 

  cd ${code_dir}
  source MODULES
  launcher_args=$(Rscript recipe_maker.R ${recipe_template} --sd=${sdate[@]} --horizon=${horizon} --expid=${expid})
  bash ${code_dir}/launch_SUNSET.R ${launcher_args} --disable_unique_ID

  ## TODO: Set up ssh to AS machine; or do it directly as part of launch_SUNSET.R?
  username=$(whoami)
  ssh ${username}@bscesautosubmit01.bsc.es "module load autosubmit/4.0.98-foss-2015a-Python-3.7.3;
    autosubmit create ${expid} --noplot;
    autosubmit refresh ${expid};
    # create must be done each time 
    autosubmit monitor ${expid};
    # Save for logging purposes (specify -fs to filter
    # jobs when ensemble, -o {pdf,png,ps,svg} for different plot format files)
    nohup autosubmit run -v ${expid} &"
}

#########
# MAIN 
#########

parse_args $@
# Retrieve startdate
get_startdate
# Launch Workflow 
launch_auto
