#!/bin/sh
#
# post_service:
# - on install, register the service;
# - on update, restart it.
#
# post_service_postponed:
# - on install, register the service;
# - on update, queue its restart at the end of rpm transaction.
#
# Copyright (C) 2021  Vladimir D. Seleznev <vseleznv@altlinux.org>
# Copyright (C) 2021  Dmitry V. Levin <ldv@altlinux.org>
# Copyright (C) 2021  Vitaly Chikunov <vt@altlinux.org>
#
# SPDX-License-Identifier: GPL-2.0-or-later

fatal()
{
	printf '%s\n' "${0##*/}: $*" >&2
	exit 1
}

append_to_postponed()
{
	local RUNDIR POSTPONED
	RUNDIR=/run/service
	POSTPONED="$RUNDIR/postponed_condrestart"

	umask 077
	mkdir -p "$RUNDIR"
	{
		flock 1
		printf '%s\n' "$*"
	} >> "$POSTPONED"
}

[ $# -eq 1 ] ||
	fatal 'usage:\n
post_service <service>\n
post_service_postponed <service>'

postpone=
if [ "${0##*/}" = "post_service_postponed" ]; then
	postpone=1
fi

[ -n "${1##*/*}" ] ||
	fatal "$1: invalid service name"

[ "$RPM_INSTALL_ARG1" -ge 1 ] 2>/dev/null ||
	fatal 'RPM_INSTALL_ARG1: invalid or undefined variable'

SYSTEMCTL=systemctl
SD_UPDATE_HELPER=/lib/systemd/systemd-update-helper
PATH=/sbin:/usr/sbin:/bin:/usr/bin

if sd_booted && "$SYSTEMCTL" --version >/dev/null 2>&1; then
	"$SYSTEMCTL" daemon-reload
	if [ "$RPM_INSTALL_ARG1" -eq 1 ]; then
		"$SYSTEMCTL" -q preset "$1"
	else
		if [ -z "$postpone" ]; then
			"$SYSTEMCTL" try-restart "$1"
		else
			if [ -x "$SD_UPDATE_HELPER" ]; then
				"$SD_UPDATE_HELPER" mark-restart-system-units "$1"
			else
				append_to_postponed "$1"
			fi
		fi
	fi
else
	if [ "$RPM_INSTALL_ARG1" -eq 1 ]; then
		chkconfig --add "$1"
	else
		chkconfig "$1" resetpriorities
		if [ -z "$postpone" ]; then
			service "$1" condrestart
		else
			append_to_postponed "$1"
		fi
	fi
fi

exit 0
