#!/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

  # Exploit the number from the member name
  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.*" | sort -n )
  AN_INC_SOURCE=$(find ${INITIAL_CONDITIONS_PATH} -name "an_R19B07.*00_inc.*" | sort -n )
  FG_SOURCE=$(find ${INITIAL_CONDITIONS_PATH} -name "fc_R19B07.*5500.*" | sort -n )

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

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


  if [ -z "${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_SOURCE}" > an_file.txt
  echo "${AN_INC_SOURCE}" > an_inc_file.txt
  echo "${FG_SOURCE}" > fg_file.txt

  # Copy the first-guess and analysis files.
  rsync -v --file-from=an_file.txt / "${COMMON_DATE_FOLDER}"
  rsync -v --file-from=an_inc_file.txt / "${COMMON_DATE_FOLDER}"
  rsync -v --file-from=fg_file.txt / "${COMMON_DATE_FOLDER}"

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