#!/bin/sh
# MoxiVue was called Moxon Metrics up to 4.1. Run by the package scripts after an upgrade from a moxon-metrics
# package: stops and retires the services under the old names (moving per-user system agents to the new name),
# and moves the apt source to moxivue.com. Safe to run more than once.
if [ -d /run/systemd/system ]; then
  systemctl disable --now moxon-metrics-helper.service >/dev/null 2>&1 || true
  # agents set up with "moxon service enable --user NAME" (system units moxon-agent@NAME)
  for w in /etc/systemd/system/*.wants/moxon-agent@*.service; do
    [ -e "$w" ] || [ -L "$w" ] || continue
    u=$(basename "$w"); inst=${u#moxon-agent@}; inst=${inst%.service}
    systemctl disable --now "$u" >/dev/null 2>&1 || true
    systemctl daemon-reload >/dev/null 2>&1 || true
    systemctl enable --now "moxivue-agent@$inst.service" >/dev/null 2>&1 || true
  done
  for u in $(systemctl list-units --all --plain --no-legend 'moxon-agent@*.service' 2>/dev/null | awk '{print $1}'); do
    systemctl stop "$u" >/dev/null 2>&1 || true
  done
fi
systemctl --global disable moxon-agent.service >/dev/null 2>&1 || true
rm -f /etc/systemd/user/*.wants/moxon-agent.service
# apt: the same signed repository, now at get.moxivue.com
L=/etc/apt/sources.list.d/moxon.list
if [ -f "$L" ] && grep -q 'moxon-archive-keyring' "$L"; then
  K=/usr/share/keyrings/moxon-archive-keyring.gpg
  if [ -f "$K" ]; then cp "$K" /usr/share/keyrings/moxivue-archive-keyring.gpg; fi
  sed -e 's#moxon-archive-keyring#moxivue-archive-keyring#g' -e 's#get\.142-93-115-168\.sslip\.io#get.moxivue.com#g' "$L" > /etc/apt/sources.list.d/moxivue.list
  rm -f "$L" "$K"
fi
exit 0
