#!/bin/bash
# Author  : Gaston Gonzalez
# Date    : 29 November 2025
# Updated : 30 November 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

# 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 HF
# 51 VARA FM
# 52 VARA FM Wide
# 54 VARA HF 2750

cat ${RMS_SRC_JSON_FILE} | jq -r '
  .Gateways[]
  | . as $gw
  | $gw.GatewayChannels[]
  | select(.Mode | IN(0, 41, 43, 50, 51, 52, 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
echo -e "${YELLOW}To update the Winlink index, perform the following as your normal user:${NC}"
echo
echo -e "${RED}DO NOT RUN THESE AS ROOT!${NC}"
echo
echo -e "${YELLOW}1. Stop the ETC API:  ${WHITE}systemctl --user stop et-service-et-api${NC}"
echo -e "${YELLOW}2. Remove the old index: ${WHITE}rm -rf /opt/emcomm-tools-api/index/rmslist${NC}"
echo -e "${YELLOW}3. Start the ETC API: ${WHITE}systemctl --user start et-service-et-api${NC}"
