#!/bin/bash -l

# This script is executed on the remote system at which the simulation will happen
# and will be used if the initial conditions are in this same remote system.
IC_DATA_IS_LOCAL=%SIMULATION.INITIAL_CONDITIONS.LOCAL%


if [ "${IC_DATA_IS_LOCAL}" != "True" ]; then
  # Get some variables provided by autosubmit.
  WORKDIR=%HPCROOTDIR%
  STARTDATE=%SDATE%
  HPCUSER=%HPCUSER%
  HPCHOST=%HPCHOST%
  # Define date directory, create it and go there
  COMMON_DATE_FOLDER=${WORKDIR}/${STARTDATE}/inidata

  AN_MEMBER=$(printf "%03d" %SIMULATION.INITIAL_CONDITIONS.MEMBER%)
  INITIAL_CONDITIONS_PARENT_FOLDER=%SIMULATION.INITIAL_CONDITIONS.PARENT_FOLDER%
  INITIAL_CONDITIONS_PATH=${INITIAL_CONDITIONS_PARENT_FOLDER}/${STARTDATE:0:8}00

  AN_SOURCE=$(find ${INITIAL_CONDITIONS_PATH} -name "an_R19B07.*00_an.${AN_MEMBER}" | sort | tail -n 1)
  AN_INC_SOURCE=$(find ${INITIAL_CONDITIONS_PATH} -name "an_R19B07.*00_inc.${AN_MEMBER}" | sort | tail -n 1)
  FG_SOURCE=$(find ${INITIAL_CONDITIONS_PATH} -name "fc_R19B07.*5500.${AN_MEMBER}" | sort | tail -n 1)

  AN_FILE=$(basename "${AN_SOURCE}")
  AN_INC_FILE=$(basename "${AN_INC_SOURCE}")
  FG_FILE=$(basename "${FG_SOURCE}")

  # Find files
  if [ ! -f "${AN_SOURCE}" ]; then
    echo "Analysis file for date ${STARTDATE} not found!"
    exit 1
  fi

  if [ ! -f "${AN_INC_SOURCE}" ]; then
    echo "Analysis increment file for date ${STARTDATE} not found!"
    exit 1
  fi


  if [ ! -f "${FG_SOURCE}" ]; then
    echo "FG file for date ${STARTDATE} not found!"
    exit 1
  fi


  # Check if we copy the initial conditions from the local system or the remote one
  # Create member folder and go there
  mkdir -p ${COMMON_DATE_FOLDER}
  cd ${COMMON_DATE_FOLDER} || exit

  # Save filenames to be used later by other scripts.
  echo "${AN_FILE}" > an_file.txt
  echo "${AN_INC_FILE}" > an_inc_file.txt
  echo "${FG_FILE}" > fg_file.txt

  # Copy the first-guess and analysis files.
  cp "${FG_SOURCE}" "${FG_FILE}"
  cp "${AN_SOURCE}" "${AN_FILE}"
  cp "${AN_INC_SOURCE}" "${AN_INC_FILE}"

  # Change permissions to read only.
  chmod 440 ./*
fi