#!/bin/bash
#
# Helper script to replay radar data (typically used by other scripts)
#
# Examples:
#     ./replay-data.sh RDU 35.8 -78.7 ${PWD}/site-data/AKL 2
#     ./replay-data.sh RDU 35.8 -78.7 ${PWD}/site-data/NPL 0
#
# HINT: Use "tmux attach || tmux" to view processes that are started up.
#
# To use this script, you will need:
#
#    data-manager-input-tool.jar - in the same directory as the script
#    data manager input service libries - typically under /usr/vaisala/radarsw/data-manager-input-service/lib
#    radar data to replay - Can be tough to find, but you can use data from any radar site.
#

declare toolsDir="$(realpath $(dirname ${0}))"
declare cmdDir="$(dirname "${toolsDir}")"

# You can export any of these variables on the command line before running the script to
# adjust values
declare siteName="${1:-${siteName:-KSC}}"
declare siteLat="${2:-${siteLat:-28.4644}}"
declare siteLon="${3:-${siteLon:--80.5547}}"
declare inputDir="${4:-${cmdDir}/site-data/AKL}"
declare -i daysBack="${5:-${daysBack:-0}}"

declare -i timeInterval=${timeInterval:-0}

# In IRIS Focus 7.0 port for data manager moved to 31000
declare dmPort=31000
declare apiUrlDef="http://localhost:${dmPort}/focus-dm/api/v2/"
declare VAISALA_RADARSW_CONFIG_DIR=${VAISALA_RADARSW_CONFIG_DIR:-/etc/vaisala/radarsw/configuration}
declare webappIni=${VAISALA_RADARSW_CONFIG_DIR}/vsoweb-override.ini
if [ -f ${webappIni} ]; then
  # See if running DM outside of K8S
  for p in 24380 34380; do
    if grep -q ^data.manager.*${p} ${webappIni} &>/dev/null; then
      dmPort=${p}
      apiUrlDef="$(grep ^data.manager.*${p} ${webappIni} | sed -e 's,.*\(http://.*\)$,\1,')"
      break
    fi
  done
fi

declare apiUrl="${apiUrl:-${apiUrlDef}}"
declare rsyncServer="${rsyncServer:-hel-fire-tlp-ci}"

# Required to find native libraries on system
export LD_LIBRARY_PATH=/usr/vaisala/radarsw/data-manager-input-service/lib:${LD_LIBRARY_PATH}

# 
declare replayJar="${toolsDir}/data-manager-input-tool.jar"

if [ ! -f "${replayJar}" ]; then
  echo "ERROR: Failed to location JAR file: ${replayJar}";
fi

export PATH="${toolsDir}:${PATH}"

declare cmd="java -jar ${replayJar} --play --site ${siteName} -lat ${siteLat} -lon ${siteLon} -i ${inputDir} --api-url ${apiUrl} --days ${daysBack} --time-interval ${timeInterval}"

echo -e "Running:

export LD_LIBRARY_PATH='${LD_LIBRARY_PATH}'
${cmd}
";
exec ${cmd}
