#!/usr/bin/env bash

: <<'END'
dhwebchatd
DigiHub APRS WebChat service wrapper - runs aprsd's webchat command
(aprsd-webchat-extension) using the config generated from $HOME/.dhinfo

Version 0.1

Steve de Bode - W0FFS - July 2026

Input:	none - runs continuously under systemd (unit: dhwebchat.service)
	reads $HOME/.config/aprsd/aprsd.conf, generated by webchatconf.py;
	connects to Direwolf's KISS-over-TCP port (localhost:8001), so a
	Direwolf-backed mode (tnc/tnc300b/tracker/digipeater/node) needs
	to be active via dhmode for messages to actually move over RF
	uses DigiHubvenv (from EnvironmentFile)
Output:	none - runs aprsd webchat until stopped
END

set -uo pipefail

UI_LIB="/usr/local/lib/digihub/dh.lib"
[ -r "$UI_LIB" ] && source "$UI_LIB" || {
  printf "\nERROR: Missing UI library: %s\n\n" "$UI_LIB" >&2
  exit 1
}

if [ -z "${DigiHubvenv:-}" ] || [ ! -x "$DigiHubvenv/bin/aprsd" ]; then
  err_section "DigiHub APRS WebChat"
  err_kv "Message" "aprsd is not installed in the DigiHub Python virtual environment."
  err_kv "Action" "sudo \$DigiHubvenv/bin/pip3 install aprsd aprsd-webchat-extension"
  printf "\n" >&2
  exit 1
fi

CONF="$HOME/.config/aprsd/aprsd.conf"

if [ ! -f "$CONF" ]; then
  err_section "DigiHub APRS WebChat"
  err_kv "Message" "Configuration not found: $CONF"
  err_kv "Action" "Turn WebChat on first, e.g.: dhwebchat on"
  printf "\n" >&2
  exit 1
fi

section "DigiHub APRS WebChat"
kv "Config" "$CONF"
kv "Port"   "8888"
printf "\n"

exec "$DigiHubvenv/bin/aprsd" webchat --config-file "$CONF"
