#!/bin/sh
# Refresh an existing headless system service, then run the per-user migration
# for every account that still has the former
# ~/.local installation. This script is called by DEB/RPM maintainer hooks.
set -u

# CLI-only servers may have a system unit instead of a graphical user session.
# Root is intentionally excluded from the desktop migration below. Refresh only
# an already-active CLI unit; package installation must not opt users into it.
if command -v systemctl >/dev/null 2>&1 \
    && systemctl --quiet is-active sufficit-ai-genius-cli.service 2>/dev/null; then
    if ! systemctl daemon-reload \
        || ! systemctl try-restart sufficit-ai-genius-cli.service; then
        echo 'Warning: Genius installed, but the CLI service restart failed. Run: systemctl restart sufficit-ai-genius-cli.service'
    fi
fi

migrator="${GENIUS_USER_MIGRATOR:-/usr/lib/sufficit-ai-genius/migrate-legacy-user}"
[ -x "$migrator" ] || exit 0

getent passwd | while IFS=: read -r user _ uid _ _ home _; do
    case "$uid" in
        ''|*[!0-9]*) continue ;;
    esac
    [ "$uid" -ge 1000 ] 2>/dev/null || continue
    [ "$uid" -lt 60000 ] 2>/dev/null || continue
    legacy_launcher="$home/.local/share/sufficit-ai-genius/genius"
    enabled_link=$(find "$home/.config/systemd/user" -maxdepth 3 -type l \
        -name 'sufficit-ai-genius.service' -print -quit 2>/dev/null || true)
    explicitly_invoked=0
    if [ "${SUDO_USER:-}" = "$user" ] || [ "${PKEXEC_UID:-}" = "$uid" ]; then
        explicitly_invoked=1
    fi
    if [ ! -f "$legacy_launcher" ] \
        && [ -z "$enabled_link" ] \
        && [ "$explicitly_invoked" -ne 1 ]; then
        continue
    fi

    runtime_dir="/run/user/$uid"
    if command -v runuser >/dev/null 2>&1; then
        runuser -u "$user" -- env \
            HOME="$home" \
            XDG_RUNTIME_DIR="$runtime_dir" \
            DBUS_SESSION_BUS_ADDRESS="unix:path=$runtime_dir/bus" \
            "$migrator" "$home" 2>/dev/null || true
        runuser -u "$user" -- env \
            HOME="$home" \
            XDG_RUNTIME_DIR="$runtime_dir" \
            DBUS_SESSION_BUS_ADDRESS="unix:path=$runtime_dir/bus" \
            systemctl --user daemon-reload 2>/dev/null || true
        runuser -u "$user" -- env \
            HOME="$home" \
            XDG_RUNTIME_DIR="$runtime_dir" \
            DBUS_SESSION_BUS_ADDRESS="unix:path=$runtime_dir/bus" \
            systemctl --user enable sufficit-ai-genius.service 2>/dev/null || true
        # `enable --now` is intentionally not used here: it is a no-op for an
        # already-active service and would leave the previous assemblies
        # running after an upgrade. restart also starts an inactive unit.
        runuser -u "$user" -- env \
            HOME="$home" \
            XDG_RUNTIME_DIR="$runtime_dir" \
            DBUS_SESSION_BUS_ADDRESS="unix:path=$runtime_dir/bus" \
            systemctl --user restart sufficit-ai-genius.service 2>/dev/null || true
    fi
done

exit 0
