#!/bin/bash -l

# Get some variables provided by autosubmit.
WORKDIR=%HPCROOTDIR%

dynamics_grid_filename=%simulation.dynamics_grid_filename%
radiation_grid_filename=%simulation.radiation_grid_filename%
external_parameters_filename=%simulation.external_parameters_filename%


STARTDATE=%SDATE%

# Example of date format "2018-06-01T00:00:00Z"
START_YEAR=%Chunk_START_YEAR%
START_MONTH=%Chunk_START_MONTH%
START_DAY=%Chunk_START_DAY%
START_HOUR=%Chunk_START_HOUR%

END_YEAR=%Chunk_END_YEAR%
END_MONTH=%Chunk_END_MONTH%
END_DAY=%Chunk_END_DAY%
END_HOUR=%Chunk_END_HOUR%

Chunk_START_DATE="${START_YEAR}-${START_MONTH}-${START_DAY}T${START_HOUR}:00:00Z"
Chunk_END_DATE="${END_YEAR}-${END_MONTH}-${END_DAY}T${END_HOUR}:00:00Z"

# Convert dates to Unix timestamps
t1_unix=$(date -d "$Chunk_START_DATE" +%s)
t2_unix=$(date -d "$Chunk_END_DATE" +%s)

# Compute difference in seconds
checkpoint_time=$(((t2_unix - t1_unix)))

# Compute number of steps
dtime=180

# Extend chunk 10 minutes to ensure checkpoint creation at the proper time
# TODO: Works but it is a bit ugly.
Chunk_END_DATE="${END_YEAR}-${END_MONTH}-${END_DAY}T${END_HOUR}:10:00Z"

MEMBER=%MEMBER%
CHUNK=%CHUNK%

# If the chunk is not the first one, start from a restart file.
if [[ "${CHUNK}" -eq "1" ]]; then
  is_restart=.false.
else
  is_restart=.true.
fi

# Define rundir
RUNDIR=${WORKDIR}/${STARTDATE}/${MEMBER}

cd ${RUNDIR} || exit

# Get AN and FG file names from file that was saved during prepare_rundir
AN_FILE=$( cat an_file.txt )
FG_FILE=$( cat fg_file.txt )
