#!/usr/bin/env bash

: <<'END'
dhardop
Turn DigiHub's ARDOP TNC (ardopcf) on or off

Version 0.2

Steve de Bode - W0FFS - July 2026

Input:  on|off|status   what to do
        -h, --help       show this help text
Output: none - manages the dhardop systemd service
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
}

usage() {
  sed -n '/^: <<'\''END'\''/,/^END$/p' "$0" | sed '1d;$d'
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" || $# -eq 0 ]]; then
  usage
  exit 0
fi

action="$1"
SERVICE="dhardop.service"

case "$action" in
  on|off|status) ;;
  *)
    printf 'Unknown action "%s". Use: on, off, or status.\n' "$action" >&2
    exit 2
    ;;
esac

if [[ "$action" == "status" ]]; then
  if command -v systemctl >/dev/null 2>&1; then
    systemctl is-active "$SERVICE" 2>/dev/null || printf 'inactive\n'
  else
    printf 'unknown\n'
  fi
  exit 0
fi

# sudo changes HOME to root's home. Resolve the invoking user's home
# from the account database before checking the DigiHub configuration.
TargetHome="$HOME"
if [[ "$EUID" -eq 0 && -n "${SUDO_USER:-}" && "$SUDO_USER" != "root" ]]; then
  TargetHome=$(getent passwd "$SUDO_USER" | cut -d: -f6)
  if [[ "$TargetHome" != /* ]]; then
    printf 'Could not resolve the home directory for %s.\n' "$SUDO_USER" >&2
    exit 1
  fi
fi
DhInfoPath="$TargetHome/.dhinfo"
need_file "$DhInfoPath" "Run install.sh to install DigiHub first."

# When invoked via sudo (e.g. by dhweb), $HOME/EUID are root's -- but
# patconf.py must write to the actual DigiHub user's $HOME/.config/pat,
# not root's. Drop back to the real user for that one step.
run_as_target_user() {
  if [[ "${EUID}" -eq 0 && -n "${SUDO_USER:-}" && "$SUDO_USER" != "root" ]]; then
    sudo -H -u "$SUDO_USER" "$@"
  else
    "$@"
  fi
}

if [[ "$action" == "on" ]]; then
  if ! command -v ardopcf >/dev/null 2>&1; then
    err_section "DigiHub ARDOP"
    err_kv "Message" "ardopcf is not installed."
    err_kv "Action" "Install it from https://www.plotlost.com/static/downloads/dependencies/ardop/, then try again."
    printf "\n" >&2
    exit 1
  fi

  # Keep Pat's ardop/hamlib_rigs wiring in sync -- harmless if Pat isn't
  # turned on yet, and not required for ardopcf itself to run, so a
  # failure here is a warning, not a reason to abort.
  if ! run_as_target_user python3 /usr/local/bin/patconf.py; then
    printf 'Warning: could not update Pat'"'"'s configuration; continuing.\n' >&2
  fi

  if ! ensure_unit_installed "$SERVICE"; then
    exit 1
  fi

  run_sudo systemctl enable --now "$SERVICE" >/dev/null 2>&1 || true
  printf 'ARDOP TNC enabled.\n'
else
  run_sudo systemctl disable --now "$SERVICE" >/dev/null 2>&1 || true
  printf 'ARDOP TNC disabled.\n'
fi
