#!/usr/bin/env bash

: <<'END'
dhdirewolf
DigiHub Direwolf TNC/digipeater/tracker/node service wrapper

Version 0.1

Steve de Bode - W0FFS - July 2026

Input:	none - runs continuously under systemd (unit: dhdirewolf.service)
	reads /etc/digihub/direwolf.conf, generated by direwolfconf.py
	for the mode selected via dhmode
Output:	none - runs Direwolf 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
}

CONF="/etc/digihub/direwolf.conf"

if [ ! -f "$CONF" ]; then
  err_section "DigiHub Direwolf"
  err_kv "Message" "Configuration not found: $CONF"
  err_kv "Action" "Select a mode first, e.g.: dhmode tnc"
  printf "\n" >&2
  exit 1
fi

if ! command -v direwolf >/dev/null 2>&1; then
  err_section "DigiHub Direwolf"
  err_kv "Message" "direwolf is not installed."
  err_kv "Action" "sudo apt-get install direwolf"
  printf "\n" >&2
  exit 1
fi

# "node" mode needs a local KISS pty for kissattach (see dhnoded) to bridge
# into the kernel AX.25 stack; Direwolf's -p flag creates it at the stable
# path /tmp/kisstnc. Other modes don't need it.
if grep -q '^# DIGIHUB_MODE=node$' "$CONF"; then
  exec direwolf -t 0 -p -c "$CONF"
else
  exec direwolf -t 0 -c "$CONF"
fi
