#!/bin/sh -e

# Parhand's interface to systemd via systemctl
# $1 - command; $2 - service;
# $3 - param (required if command=toggle)
# Command 'toggle' example:
# toggle vftpd.service root_Network_FTP_Enabled

. /lib/rcscripts/sh/error.sh

[ $# -ge 2 ] && [ "$1" ] && [ "$2" ] ||
	error "Must have at least two arguments"

lfd=/var/lock/parhand2systemctl
lf=$lfd/$2
# Create lockfile directory if it does not already exist
[ -d $lfd ] || mkdir -p $lfd

run=systemctl
( flock 9;
	case $1 in
		toggle)
			param_val=
			if [ -z "$3" ]; then
				error "Will not $1 $2: the param argument is missing"
			else
				eval param_val=\$$3
			fi
			[ "$param_val" ] || error "Environment variable is not set"

			case $param_val in
				yes)
					$run start $2 || error "Failed to start $2"
					$run daemon-reload || error "Failed to reload after starting $2"
					;
				no)
					$run stop $2 || error "Failed to stop $2"
					$run daemon-reload || error "Failed to reload after stopping $2"
					;
				*)
					error "Invalid/unset value of '$param_val'"
					;
			esac
			;
		*)
			$run $1 $2 || error "Failed to $1 $2"
			;
	esac
) 9>$lf