#!/bin/bash

# Run after systemd's 30-systemd-daemon-reload-user.hook. Image builds and
# offline installations have no running managers and must remain untouched.
if systemd-detect-virt --chroot || ! systemd-notify --booted; then
  exit 0
fi

managers=$(systemctl list-units 'user@*.service' --state=running --no-legend --plain) || exit 1
result=0
while read -r unit _; do
  [[ $unit =~ ^user@([0-9]+)\.service$ ]] || continue
  user_id=${BASH_REMATCH[1]}
  # Use the user's manager rather than pacman's root session. try-restart
  # never starts a stopped service or changes its enablement.
  if ! systemctl --user --machine="$user_id@.host" try-restart owed.service; then
    echo ":: Could not restart OWE for user $user_id; restart owed.service in that user session." >&2
    result=1
  fi
done <<< "$managers"
exit "$result"
