
#!/usr/bin/env bash
# Usage: APRSFI_KEY=your_key ./aprs_receivers_lookup.sh /path/to/*.csv
# Deps: curl, jq   Install jq on Ubuntu: sudo apt-get install -y jq

set -euo pipefail

if ! command -v jq >/dev/null; then
  echo "Please install jq (sudo apt-get install -y jq)"; exit 1
fi
if ! command -v curl >/dev/null; then
  echo "Please install curl"; exit 1
fi
: "${APRSFI_KEY:?Please export APRSFI_KEY=your_aprsfi_api_key}"

FILES=${*:-./*.csv}
tmpdir="$(mktemp -d)"; trap 'rm -rf "$tmpdir"' EXIT

echo "→ Scanning CSVs…"
# Pull unique IGate/receiver calls after qAR, or qAO, in the PATH field (col 4)
awk -v FPAT='([^,]+)|(\"[^\"]+\")' '
  NR>1 {
    f=$4; gsub(/"/,"",f);
    n=split(f,a,",");
    for(i=1;i<=n;i++){
      if (a[i]=="qAR" || a[i]=="qAO"){
        if (i+1<=n){
          call=a[i+1];
          gsub(/\*/,"",call); gsub(/^[ \t]+|[ \t]+$/,"",call);
          if (call!="") print call;
        }
      }
    }
  }' $FILES | sort -u > "$tmpdir/receivers.txt"

# Also capture unique TO field (col 3) you asked about (may include MIC-E "STUV.." etc.)
awk -v FPAT='([^,]+)|(\"[^\"]+\")' 'NR>1{ t=$3; gsub(/"/,"",t); if(t!="") print t }' $FILES \
| sort -u > "$tmpdir/to_list.txt"

query_loc () {
  local name="$1"
  curl -s "https://api.aprs.fi/api/get?what=loc&name=${name}&format=json&apikey=${APRSFI_KEY}"
}

echo "name,lat,lon,type,symbol_table,symbol,lasttime_iso,comment" > receivers_info.csv
echo "→ Looking up $(wc -l < "$tmpdir/receivers.txt") receivers on aprs.fi…"

while read -r C; do
  [ -z "$C" ] && continue
  json="$(query_loc "$C")" || json='{}'
  if [ "$(echo "$json" | jq -r '.result // "fail"')" != "ok" ] || [ "$(echo "$json" | jq '.found // 0')" -eq 0 ]; then
    echo "$C,,,,,,," >> receivers_info.csv
    continue
  fi
  # Extract with jq, convert epoch to ISO
  name=$(echo "$json" | jq -r '.entries[0].name // ""')
  lat=$(echo  "$json" | jq -r '.entries[0].lat // ""')
  lon=$(echo  "$json" | jq -r '.entries[0].lng // ""')
  typ=$(echo  "$json" | jq -r '.entries[0].type // ""')
  stab=$(echo "$json" | jq -r '.entries[0].symboltable // ""')
  sym=$(echo  "$json" | jq -r '.entries[0].symbol // ""')
  last=$(echo "$json" | jq -r '(.entries[0].lasttime // 0) | tonumber')
  comm=$(echo "$json" | jq -r '.entries[0].comment // ""' | tr '\n' ' ' | tr -d '\r')
  if [ -n "$last" ] && [ "$last" -gt 0 ] 2>/dev/null; then
    last_iso=$(date -u -d @"$last" +"%Y-%m-%dT%H:%M:%SZ")
  else
    last_iso=""
  fi
  printf "%s,%s,%s,%s,%s,%s,%s,%s\n" "$name" "$lat" "$lon" "$typ" "$stab" "$sym" "$last_iso" "$comm" >> receivers_info.csv
done < "$tmpdir/receivers.txt"

echo "→ Wrote receivers_info.csv ✅"

# Optional: try to look up the unique TO values too (many will be MIC-E aliases, expect blanks)
echo "name,lat,lon,type,symbol_table,symbol,lasttime_iso,comment" > to_info.csv
echo "→ (Optional) Looking up $(wc -l < "$tmpdir/to_list.txt") unique TO values…"
while read -r C; do
  [ -z "$C" ] && continue
  json="$(query_loc "$C")" || json='{}'
  if [ "$(echo "$json" | jq -r '.result // "fail"')" != "ok" ] || [ "$(echo "$json" | jq '.found // 0')" -eq 0 ]; then
    echo "$C,,,,,,," >> to_info.csv
    continue
  fi
  name=$(echo "$json" | jq -r '.entries[0].name // ""')
  lat=$(echo  "$json" | jq -r '.entries[0].lat // ""')
  lon=$(echo  "$json" | jq -r '.entries[0].lng // ""')
  typ=$(echo  "$json" | jq -r '.entries[0].type // ""')
  stab=$(echo "$json" | jq -r '.entries[0].symboltable // ""')
  sym=$(echo  "$json" | jq -r '.entries[0].symbol // ""')
  last=$(echo "$json" | jq -r '(.entries[0].lasttime // 0) | tonumber')
  comm=$(echo "$json" | jq -r '.entries[0].comment // ""' | tr '\n' ' ' | tr -d '\r')
  if [ -n "$last" ] && [ "$last" -gt 0 ] 2>/dev/null; then
    last_iso=$(date -u -d @"$last" +"%Y-%m-%dT%H:%M:%SZ")
  else
    last_iso=""
  fi
  printf "%s,%s,%s,%s,%s,%s,%s,%s\n" "$name" "$lat" "$lon" "$typ" "$stab" "$sym" "$last_iso" "$comm" >> to_info.csv
done < "$tmpdir/to_list.txt"

echo "→ Wrote to_info.csv (expect many blanks for MIC-E TO aliases) ✅"
