#!/bin/sh -e

# Parhand's interface to systemd via systemctl
# $1 - command; $2 - service; $3 - param (optional)
# Command 'toggle' example:
# a) toggle vftpd.service
# b) 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
				IFS==
				while read var val; do
					case $var in
						root_*_Enabled)
							val=${val#\'}
							val=${val%\'}
							break
							;
						*)
							val=
							;
					esac
				done <<-EOF
					$(set)
				EOF
				[ -z "$val" ] || param_val=$val
			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