#!/bin/bash 
source /etc/profile.d/modules.sh
#set -eu
#set -v

function usage {
  echo "Usage: $0 -r=<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 " "
}
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
        ;;
      # -str=*|--stream=*)
      #   stream="${i#*=}"
      #   shift # past argument=value
      #   ;;
      ## TODO: Is this needed?
      -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
}

function check_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
        if [[ ${stream} == "fcst" ]]; then
          sdate+=($dl_date)
        elif [[ ${stream} == "hcst" ]]; then
          sdate+=($(date --date="$dl_date +14 day" +%Y%m%d))
        else
          echo "Stream neither fcst nor hcst"
          exit 1
        fi
      elif [[ ${week_day} == Mon && ${stream} == "hcst" ]]; then
        sdate+=($(date --date="$dl_date +14 day" +%Y%m%d))
      else
        usage
        exit 0
      fi
    else
      sdate=${dl_date:0:6}01
    fi
  done
}

function launch_auto {
  code_dir=./
  # code_dir="/esarchive/autosubmit/${expid}/conf/"

  source ${code_dir}/MODULES
  launch_args=$(Rscript ${code_dir}/recipe_maker.R ${recipe_template} --sd=${sdate} --expid=${expid})

  ## LAST LINE EDITED
  echo "Launching operational..."
  echo "Recipe template: ${recipe_template}"
  echo "Main script: ${script}"
  echo "Start date: ${sdate}"
  echo "Using EXPID:  ${expid}"
  echo "[INFO] Running SUNSET launcher from ${code_dir}" 
  # sed -i 's/^DATELIST =.*/DATELIST = '"$(echo ${SDATE[@]})"'/' expdef_${EXPID}.conf
  # sed -i 's/^STREAM =.*/STREAM = '${STREAM}'/' proj_${EXPID}.conf
  bash ${code_dir}/launch_SUNSET.sh ${launch_args}
  ssh $(whoami)@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 $@

check_startdate
#
## Launch Workflow 
launch_auto
