# shellcheck shell=bash

# The user side is a path unit plus the one-shot it triggers. The path unit is
# the one that must be enabled: enabling only the service would publish the
# layout once at login and never notice a later change.
_for_session_users() {
	local unit=$1 action=$2 uid user
	while read -r uid user _; do
		[[ $uid =~ ^[0-9]+$ && $uid -ge 1000 ]] || continue
		[[ $user =~ ^[A-Za-z_][A-Za-z0-9_.-]*[$]?$ ]] || continue
		/usr/bin/systemctl --user --machine="${user}@.host" "$action" \
			"$unit" >/dev/null 2>&1 || true
	done < <(/usr/bin/loginctl list-users --no-legend --no-pager 2>/dev/null)
}

# Arm the watch and publish the current layout for users who are already logged
# in, so neither install nor upgrade waits for the next login.
_activate_for_sessions() {
	_for_session_users bigcedilla-agent.path start
	_for_session_users bigcedilla-agent.service start
}

post_install() {
	/usr/bin/systemctl daemon-reload >/dev/null 2>&1 || true
	/usr/bin/systemctl preset bigcedilla.service >/dev/null 2>&1 || true
	if /usr/bin/systemctl is-enabled --quiet bigcedilla.service; then
		/usr/bin/systemctl start bigcedilla.service >/dev/null 2>&1 || true
	fi

	/usr/bin/systemctl --global preset bigcedilla-agent.path >/dev/null 2>&1 || true
	/usr/bin/systemctl --global preset bigcedilla-agent.service >/dev/null 2>&1 || true
	if /usr/bin/systemctl --global is-enabled --quiet bigcedilla-agent.path; then
		_activate_for_sessions
	fi

	cat <<'EOF'

==> bigcedilla installed (evdev/uinput cedilla fix).
==> It fixes `'` + c -> ç below the compositor for every application.
==>   root daemon:   systemctl status bigcedilla.service
==>   layout watch:  systemctl --user status bigcedilla-agent.path
EOF
}

post_upgrade() {
	/usr/bin/systemctl daemon-reload >/dev/null 2>&1 || true
	/usr/bin/systemctl try-restart bigcedilla.service >/dev/null 2>&1 || true

	# Upgrading from 0.x, where bigcedilla-agent.service was a resident poller:
	# that unit is a one-shot now, so the old long-running instance must be
	# stopped and the watching handed over to the path unit. Presetting the path
	# unit is what moves the --global enable off the service.
	/usr/bin/systemctl --global preset bigcedilla-agent.path >/dev/null 2>&1 || true
	_for_session_users bigcedilla-agent.service stop
	_activate_for_sessions
}

pre_remove() {
	/usr/bin/systemctl disable --now bigcedilla.service >/dev/null 2>&1 || true
	/usr/bin/systemctl --global disable bigcedilla-agent.path >/dev/null 2>&1 || true
	/usr/bin/systemctl --global disable bigcedilla-agent.service >/dev/null 2>&1 || true
	_for_session_users bigcedilla-agent.path stop
	_for_session_users bigcedilla-agent.service stop
}

post_remove() {
	/usr/bin/systemctl daemon-reload >/dev/null 2>&1 || true
}
