#!/bin/bash
#
# Script prints to stdout list of registered in Linux system services in format:
# service_name (running|stopped)
# where 'running' means service is enabled for default runlevel while
# 'stopped' - disabled.
#
# Copyright (c) 2010-2017, Parallels International GmbH
# Copyright (c) 2017-2019 Virtuozzo International GmbH. All rights reserved.
#
# This file is part of vzreport. It's free software; you can redistribute
# it and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the License,
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
# Our contact details: Virtuozzo International GmbH, Vordergasse 59, 8200
# Schaffhausen, Switzerland.
#

SERVICE="/usr/bin/service"

function list_services_systemd
{
	TYPES="service,timer,path,automount,socket"

	/bin/systemctl -a --type=$TYPES --no-pager --no-legend | \
		sort -k3 | \
		awk '$1 !~ "systemd" && $2 != "not-found" \
			{
				sub("\\.(.*)", "", $1);
				if (x[$1]++ == 0)
				{
					if ($3 == "active")
						print $1" running";
					else
						print $1" stopped";
				}
			}'
}

function list_services_chkconfig
{
	xinetd_enabled=0
	runlevel=`/sbin/runlevel | awk '{print $2}'`

	if [ -z "$runlevel" ]; then
		# we failed to determine current runlevel
		return;
	fi

	/sbin/chkconfig --list | \
		sed -n "s/^\(\w\+\)\s\+.*$runlevel:\(\w\+\).*$/\1 \2/p;
			/^\s\+\w\+/p" | \
	while read service state; do
		if `echo $service | grep -q ":$"`; then
			# xinetd based service
			if [ $xinetd_enabled -ne 1 ]; then
				continue
			fi
			echo -n "${service%:}"
		else
			echo -n "$service"
		fi

		if [ $state == "on" ]; then
			echo " running"
		else
			echo " stopped"
		fi

		if [ "$service" == "xinetd" -a "$state" == "on" ]; then
			xinetd_enabled=1
		fi
	done
}

function list_services_service
{
	$SERVICE --status-all 2>&1 | \
		sed -n "s/^ \[ \(.\) \]\s\+\(.*\)$/\2 \1/p" | \
	while read service state; do
		echo -n "$service"
		if [ "$state" == "+" ]; then
			echo " running"
		elif [ "$state" == "-" ]; then
			echo " stopped"
		else
			echo " unknown"
		fi
	done
}

if [ -x /bin/systemctl ]; then
	list_services_systemd
elif [ -x /sbin/chkconfig ]; then
	list_services_chkconfig
elif [ -x $SERVICE ]; then
	list_services_service
elif [ -x /usr/sbin/service ]; then
	SERVICE="/usr/sbin/service"
	list_services_service
fi
