#!/usr/bin/env bash

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

set -e

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

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

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

	if [ "${realservice}" = "" ]; then
		abort 2 "Cannot find service that matches ${pattern}"
	fi
else
	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
fi

systemctl "${action}" "${realservice}"
