#!/bin/sh
# hamthings-dmrhosts — rigenera gli elenchi host di Pi-Star coi master HamThings, presi dalla
# STESSA API che genera il JSON dei master (/v2/master, solo Type=0 pubblici: 2223/2229 gia'
# esclusi a monte). Girato al boot/postinst e da /etc/cron.daily (stessa cadenza degli host Pi-Star).
#
# Gestisce DUE tecnologie (un reflector/master per ciascun master pubblico):
#   DMR -> DMR_Hosts.txt  righe:  HamThings_<id> <id> <addr> passw0rd 62031
#   YSF -> YSFHosts.txt   righe:  <id>;HamThings-<id>;HamThings YSF <id>;<addr>;42000;000;
#         (nome <=16 char: YSFGateway tronca il nome del reflector a 16 -> nomi lunghi collidono)
# Per ognuna scrive /root/<file> (OVERRIDE che HostFilesUpdate.sh appende) e aggiorna la lista
# LIVE /usr/local/etc/<file> (dropdown, effetto immediato). Idempotente.

API="${HAMTHINGS_MASTERS_URL:-https://hamthings.it/v2/master}"
J=$(curl -fsS --max-time 15 "$API" 2>/dev/null) || { echo "[hamthings-hosts] API $API non raggiungibile, salto"; exit 0; }

# id+address di ogni master (una riga "id addr"). printf '%s\n' aggiunge il newline finale che
# manca nel JSON dell'API (altrimenti 'while read' scarterebbe l'ultimo master).
PAIRS=$(printf '%s\n' "$J" | sed 's/},{/}\n{/g' | while IFS= read -r obj; do
  id=$(printf '%s' "$obj" | grep -oE '"id"[^,]*'       | grep -oE '[0-9]+' | head -1)
  ad=$(printf '%s' "$obj" | grep -oE '"address":"[^"]+"' | sed 's/.*:"//; s/"$//')
  [ -n "$id" ] && [ -n "$ad" ] && echo "$id $ad"
done)
[ -n "$PAIRS" ] || { echo "[hamthings-hosts] nessun master dall'API, salto"; exit 0; }

DMR_FRAG=$(echo "$PAIRS" | while read -r id ad; do printf 'HamThings_%s\t%s\t%s\tpassw0rd\t62031\n' "$id" "$id" "$ad"; done)
YSF_FRAG=$(echo "$PAIRS" | while read -r id ad; do printf '%s;HamThings-%s;HamThings YSF %s;%s;42000;000;\n' "$id" "$id" "$id" "$ad"; done)

# disco rw se serve (Pi-Star e' ro di default)
RW=0; if ! touch /root/.hnw 2>/dev/null; then mount -o remount,rw / 2>/dev/null && RW=1; else rm -f /root/.hnw; fi

# writer: <override> <live> <grep-strip-pattern> <frag> <intestazione-override>
publish(){ OVR="$1"; LIVE="$2"; STRIP="$3"; FRAG="$4"; HDR="$5"
  { echo "$HDR"; echo "$FRAG"; } > "$OVR"
  [ -f "$LIVE" ] && { grep -v "$STRIP" "$LIVE"; echo "$FRAG"; } > "$LIVE.hnw" && mv "$LIVE.hnw" "$LIVE"
}
HDR="# HamThings masters (auto, da $API) — NON modificare a mano"
publish /root/DMR_Hosts.txt /usr/local/etc/DMR_Hosts.txt '^HamThings_'        "$DMR_FRAG" "$HDR"
publish /root/YSFHosts.txt  /usr/local/etc/YSFHosts.txt  ';HamThings-'        "$YSF_FRAG" "$HDR"

[ "$RW" = 1 ] && mount -o remount,ro / 2>/dev/null
N=$(echo "$PAIRS" | grep -c .)
echo "[hamthings-hosts] $N master HamThings aggiornati (DMR + YSF, override + lista live)"
exit 0
