#!/usr/bin/env bash

: <<'END'
dhconsoled
DigiHub web console service wrapper - runs ttyd to give a
browser-based terminal running as the DigiHub operator account

Version 0.1

Steve de Bode - W0FFS - July 2026

Input:	none - runs continuously under systemd (unit: dhconsole.service,
	as the operator account -- see dhconsole.service's User= directive)
Output:	none - runs ttyd 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 ! command -v ttyd >/dev/null 2>&1; then
  err_section "DigiHub Console"
  err_kv "Message" "ttyd is not installed."
  err_kv "Action" "Install it from https://www.plotlost.com/static/downloads/dependencies/ttyd/"
  printf "\n" >&2
  exit 1
fi

PORT=7681

section "DigiHub Console"
kv "Port" "$PORT"
printf "\n"

# dhconsole.service's User= directive already runs this whole process
# as the DigiHub operator account, so ttyd just execs a login shell
# directly -- no login(1)/PAM step, no username/password prompt.
# DigiHub already assumes a trusted-network, no-auth model for every
# other dhweb page (dhmode, dhrig, dhpat, ...); the console follows
# the same one instead of being the one page that asks. Don't expose
# DigiHub to the open internet -- see man dhconsole for why.
#
# -W/--writable: ttyd is read-only by default (browser keystrokes are
# ignored, not just the login prompt) -- without it the console loads
# but nothing typed ever reaches the shell.
exec ttyd -p "$PORT" -W bash -l
