#!/bin/bash
# Author  : Gaston Gonzalez
# Date    : 29 November 2025
# Updated : 1 December 2025
# Purpose : Generates a denormalized Winlink RMS channel data set from
#           Pat Winlink's JSON definition. Each line represents a single
#           Winlink RMS channel. This generated file is the source for
#           building the Winlink search index.
source /opt/emcomm-tools/bin/et-common

RMS_SRC_JSON_FILE=~/.local/share/pat/rmslist.json
RMS_DATA_OUT_FILE=/opt/emcomm-tools-api/data/rmslist.csv
RMS_INDEX_DIR=/opt/emcomm-tools-api/index/rmslist

# Return a denormalized list of RMS stations filtered by the supported
# Winlink modes in EmComm Tools Community.
#
#  0 Packet 1200
# 41 ARDOP 500
# 43 ARDOP 2000
# 50 VARA 2300 (HF standard)
# 51 VARA FM
# 52 VARA FM  WIDE
# 53 VARA 500 (HF narrow)
# 54 VARA 2750 (HF tactical)

cat ${RMS_SRC_JSON_FILE} | jq -r '
  .Gateways[]
  | . as $gw
  | $gw.GatewayChannels[]
  | select(.Mode | IN(0, 41, 43, 50, 51, 52, 53, 54))
  | [
      $gw.BaseCallsign,
      $gw.Callsign,
      $gw.Latitude,
      $gw.Longitude,
      .SupportedModes,
      .Mode,
      .Frequency
    ]
    | join("|")
' > ${RMS_DATA_OUT_FILE}

LINES=$(wc -l $RMS_DATA_OUT_FILE | awk '{print $1}')
echo "Created RMS dataset: ${RMS_DATA_OUT_FILE} with ${LINES} records."

echo "Stopping ET API..."
systemctl --user stop et-service-et-api 

sleep 3
echo "Removing old Winlink index..."
[[ -e ${RMS_INDEX_DIR} ]] && rm -rf /opt/emcomm-tools-api/index/rmslist

# ET API will rebuild the Winlink index on startup. It takes a few seconds.
start_and_wait_for_service et-service-et-api 
