#!/usr/bin/env bash

action="$1"
service="$2"

set -e

. /usr/share/dosis2/bin/shell-support-functions

OS="`getos`"

if [ "`echo \"${service}\" | cut -d':' -f1`" = ".regex" ]; then
	pattern="`echo \"${service}\" | cut -d':' -f2`"

	if [ "${OS}" = "CentOS" ]; then
		realservice="`chkconfig | awk '{print $1}' | grep -i -E \"${pattern}\" | head -1`"
	elif [ "${OS}" = "Ubuntu" ]; then
		realservice="`systemctl list-unit-files | awk '{print $1}' | cut -d. -f1 | grep -i -E \"${pattern}\" | head -1`"
	else
		abort 1 "Unsupported OS: ${OS}"
	fi

	if [ "${realservice}" = "" ]; then
		abort 2 "Cannot find service that matches ${pattern}"
	fi
else
	if [ "${OS}" = "CentOS" ]; then
		servicesearch="${service}"
		servicesearch="${servicesearch//_/-}"
		servicesearch="${servicesearch//-/[_-]}"
		realservice="`chkconfig | awk '{print $1}' | grep -i \"^${servicesearch}$\" | head -1`"
	elif [ "${OS}" = "Ubuntu" ]; then
		servicesearch="${service}"

		if echo "${service}" | grep -q '@'; then
			servicesearch="`echo \"${servicesearch}\" | cut -d'@' -f1`"
			servicesearch="${servicesearch}@"
		fi

		servicesearch="${servicesearch//_/-}"
		servicesearch="${servicesearch//-/[_-]}"

		realservice="`systemctl list-unit-files | awk '{print $1}' | cut -d. -f1 | grep -i \"^${servicesearch}$\" | head -1`"

		if [ "${realservice}" != "" ]; then
			# if there was previously an @ marker
			if echo "${service}" | grep -q '@'; then
				# the real service name will probably have something else at the end
				# for example: openvpn@dev_alex, will refer to realservice=openvpn@.service
				# so we need to join this with what we wanted originally
				realservice="`echo \"${realservice}\" | cut -d'@' -f1`@`echo \"${service}\" | cut -d'@' -f2`"
			fi
		else
			abort 2 "Cannot find service for ${service} or one similar enough"
		fi
	else
		abort 1 "Unsupported OS: ${OS}"
	fi
fi

if [ "${OS}" = "CentOS" ]; then
    if [ "${action}" = "enable" ]; then
        /sbin/chkconfig --level 345 "${realservice}" on
    elif [ "${action}" = "disable" ]; then
        /sbin/chkconfig "${realservice}" off
    elif [ "${action}" = "is-enabled" ]; then
    	for i in `seq 2 8`; do
    		conf="`/sbin/chkconfig --list \"${realservice}\" | awk -v pos="${i}" '{print $pos}' | cut -d: -f2`"
    		if [ "${conf}" = "on" ]; then
    			echo "enabled"
    			exit 0
    		fi
    	done
    	echo "disabled"
    	exit 1
    else
	    service "${realservice}" "${action}"
	fi
elif [ "${OS}" = "Ubuntu" ]; then
	systemctl "${action}" "${realservice}"
else
	abort 1 "Unsupported OS"
fi
