#
# Helper functions replated to replaying radar data (source this in, don't call direct)
#

declare cmdDir="${cmdDir:--$(dirname "$(realpath "$(dirname ${0})")")}"
declare toolsDir="${cmdDir}/tools"
declare siteDir="${cmdDir}/site-data"
declare dataDir="${siteDir}/AKL"

# 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}}"

# In IRIS Focus 7.0 port for data manager temporarily moved to 31000 for NodePort access outside of K8S
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 -i daysBack="${daysBack:-0}"
declare rsyncServer="${rsyncServer:-hel-fire-tlp-ci.rd.vaisala.com}"

# 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"

random_datadir() {
  declare -a dirs=( $(ls ${siteDir} 2>/dev/null) )
  declare -i cnt=${#dirs[@]}
  if ((cnt == 0)); then
    return 1
  fi

  declare -i tn="1$(date +%N)";
  declare -i idx=$(( tn % cnt ))
  dataDir="${siteDir}/${dirs[idx]}";
  #echo "cnt=${cnt}  idx=${idx}  dataDir=${dataDir}"
  return 0
}

find_datadir() {
  declare radar="${1:-AKL}";
  declare dir="${2}";
  dataDir=""

  if [ "${dir}" != "" ] && [ -d "${dir}" ]; then
    dataDir="${dir}";
    return 0;
  fi

  if [ -d "${siteDir}/${radar}" ]; then
    dataDir="${siteDir}/${radar}"
    return 0
  fi

  if [ "${dir}" != "" ] && [ -d "${siteDir}/${dir}" ]; then
    dataDir="${siteDir}/${dir}"
    return 0
  fi

  # Directory not found, try to rsync from server
  if [ ! -d "${dataDir}" ]; then
    echo -e "Downloading ${radar} radar data"
    if rsync_datadir "${radar}"; then
      return 0;
    fi
    echo "Data directory ${radar} not found on ${rsyncServer}"
    
    declare tag="$(basename "${dir}")"
    if [ "${tag}" != "" ]; then
      echo -e "Downloading ${tag} radar data for ${radar} radar"
      if rsync_datadir "${tag}"; then
        return 0
      fi
      echo "Data directory ${tag} for radar ${radar} not found on ${rsyncServer}"
    fi

    echo -e "Looking for random radar data for ${radar} radar under: ${siteDir}"
    if random_datadir; then
      return 0
    fi

    echo -e "Downloading AKL radar data for ${radar}"
    if rsync_datadir AKL; then
      return 0
    fi
    echo "Data directory ${tag} for radar ${radar} not found on ${rsyncServer}"
  fi

  [ -d "${dataDir}" ]
}

rsync_datadir() {
  declare tag="$(basename "${1}")"
  if [ "${tag}" == "" ]; then
    return 1
  fi

  install -d -D ${siteDir};
  declare cmd="rsync -ah --copy-links 'rsync://${rsyncServer}/radar-replay/site-data/${tag}' '${siteDir}'"
  if ! eval "${cmd}" 2>/dev/null; then
    return 1
  fi
  if [ -d "${siteDir}/${tag}" ]; then
    dataDir="${siteDir}/${tag}"
    return 0
  fi
  return 1
}

update_radar_centers() {
  declare lonLat="${1}"
  declare centersFile="${VAISALA_RADARSW_CONFIG_DIR}/radar_centers.properties"

  if [ ! -f "${centersFile}" ]; then
    echo "Failed to update radar centers, missing: ${centersFile}"
    return 1
  fi

  if grep -q -- "=${lonLat}" "${centersFile}" &>/dev/null; then
    echo "Skipping radar centers update, found lon, lat (${lonLat}) already in ${centersFile}"
    return 0
  fi

  declare -i mapId=$(cat "${centersFile}" | awk -- 'BEGIN { maxId=74000; }
  $1 > maxId { maxId = $1; }
  END { printf("%d", maxId + 1); }')


  echo "${mapId}=${lonLat}" >> "${centersFile}"
  echo "Added \"${mapId}=${lonLat}\" to radar centers file ${centersFile}"
  return 0
}

add_radar() {
  declare name="${1}";
  declare lat="${2}";
  declare lon="${3}";
  declare dataName="${4}";
  
  declare pid="";
  if pid="$(pgrep --full "site ${name}")"; then
    echo "Simulator already running for ${name} with PID ${pid}";
  else
    if ! find_datadir ${name} "${dataName}"; then
      echo "***ERROR*** Failed to find/download data for ${name} radar"
      return 1
    fi
    declare cmd="${toolsDir}/replay-data.sh ${name} ${lat} ${lon} ${dataDir} ${daysBack}"
    echo "Starting up simulator via: ${cmd}"
    
    tmux new-window -n "${name}" "${cmd}"
  fi

  update_radar_centers "${lon}, ${lat}"
}

setup_tmux() {
  if ! tmux list-sessions &>/dev/null; then
    if ! tmux new-session -d; then
      echo -e "***ERROR*** Failed to start up tmux.

Maybe you need to: \"yum -y install tmux\"
"
      exit 1;
    fi
  fi
}
