#!/bin/sh
# After installing the .deb (postinst configure) or the .rpm (%post 1 / 2): the service
# account, /etc/verityrf with its configuration and env file when they are missing (an existing
# one is never replaced), the udev rules and systemd's view of the units. The services are not
# enabled; on an upgrade a running one is restarted.
set -e
case "$1" in
  configure) upgrade=$([ -n "${2:-}" ] && echo 1 || echo 0) ;;
  1) upgrade=0 ;;
  2) upgrade=1 ;;
  *) exit 0 ;;
esac

if command -v systemd-sysusers >/dev/null 2>&1; then
  systemd-sysusers verityrf.conf || true
fi
if ! getent passwd verityrf >/dev/null; then
  for g in audio dialout plugdev; do getent group "$g" >/dev/null || groupadd -r "$g" || true; done
  useradd -r -U -d /var/lib/verityrf -M -s /usr/sbin/nologin -c "VerityRF Modem" \
    -G audio,dialout,plugdev verityrf
fi

install -d -m 0750 -o root -g verityrf /etc/verityrf
if [ ! -e /etc/verityrf/verityrf.toml ]; then
  install -m 0660 -o root -g verityrf /usr/share/verityrf/verityrf.toml /etc/verityrf/verityrf.toml
fi
if [ ! -e /etc/verityrf/env ]; then
  install -m 0640 -o root -g verityrf /usr/share/verityrf/env /etc/verityrf/env
fi

if [ -d /run/udev ] && command -v udevadm >/dev/null 2>&1; then
  udevadm control --reload-rules || true
  udevadm trigger --action=change --subsystem-match=hidraw --subsystem-match=tty \
    --subsystem-match=usb || true
fi
if [ -d /run/systemd/system ]; then
  systemctl daemon-reload || true
  if [ "$upgrade" = 1 ]; then
    systemctl try-restart verityrf.service verityrf-observer.service || true
  fi
fi

if [ "$upgrade" = 0 ]; then
  cat <<'MSG'

VerityRF Modem: the headless modem can run as a service (not enabled):
  system service (ALSA): edit /etc/verityrf/verityrf.toml (station.mycalls, audio.input/output,
                         ptt), then  sudo systemctl enable --now verityrf
                         log: journalctl -u verityrf -f   web page: http://127.0.0.1:8320/
  user service (desktop, PulseAudio/PipeWire):  systemctl --user enable --now verityrf
  observer:              sudo systemctl enable --now verityrf-observer  (page on port 8321)
MSG
fi
exit 0
