#!/bin/sh

# This script is mostly compatible with Red Hat's service script,
# version 0.91.  However, it is not so ugly and support for option
# --status-all has been intentionally dropped.

PATH=/sbin:/usr/sbin:/bin:/usr/bin
export PATH

VERSION="service version 0.91-alt"
SERVICEDIR=/etc/init.d
SYSTEMCTL=/bin/systemctl
SYSTEMD_SERVICE_DIR=/lib/systemd/system
SYSTEMD_CGROUP_DIR=/sys/fs/cgroup/systemd
SERVICE=
OPTIONS=

info()
{
	printf %s\\n "${0##*/}: $*" >&2
}

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

usage()
{
	[ "$1" = 0 ] || exec >&2
	echo "usage: ${0##*/} --help | --version | service_name [command | --full-restart]"
	[ -n "$1" ] && exit "$1" || exit
}

systemd_status=
systemd_is_active()
{
	if [ -z "$systemd_status" ]; then
		[ -x "$SYSTEMCTL" -a \
		  -d "$SYSTEMD_CGROUP_DIR" ] &&
		mountpoint -q "$SYSTEMD_CGROUP_DIR"
		systemd_status=$?
	fi
	return $systemd_status
}

check_service()
{
	[ -n "${SERVICE##*/*}" ] ||
		fatal "$SERVICE: Invalid service name"

	[ -x "$SERVICEDIR/$SERVICE" ] && return 0

	[ -f "$SYSTEMD_SERVICE_DIR/$SERVICE.service" ] &&
		systemd_is_active &&
		return 0

	fatal "$SERVICE: Unrecognized service"
}

if [ $# -eq 0 ]; then
	usage 1
fi

if [ $# -eq 2 -a "$2" = "--full-restart" ]; then
	SERVICE="$1"
	check_service
	cd / || exit
	"$SERVICEDIR/$SERVICE" stop
	"$SERVICEDIR/$SERVICE" start
	exit $?
fi

case "$1" in
	--help|-h)
		usage 0
		;;
	--version|-V )
		echo "$VERSION"
		exit 0
		;;
	-*)
		info "$1: Invalid option"
		usage 1
		;;
	*)
		SERVICE="$1"
		shift
		check_service
		cd / || exit
		if systemd_is_active; then
			exec "$SYSTEMCTL" "$@" "$SERVICE.service"
		else
			exec "$SERVICEDIR/$SERVICE" "$@"
		fi
		exit
		;;
esac
