#!/sbin/openrc-run
# Copyright 1999-2015 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

extra_started_commands="checkconfig reload"

CRD=/opt/google/chrome-remote-desktop/chrome-remote-desktop

depend() {
	need net
	use logger
}

checkconfig() {
	local ret=0
	if [ -z "${CHROME_REMOTING_USERS}" ] ; then
		eerror "You must set CHROME_REMOTING_USERS in /etc/conf.d/${SVCNAME} first"
		ret=1
	else
		local user
		for user in ${CHROME_REMOTING_USERS} ; do
			if ! id "${user}" >/dev/null ; then
				eerror "Invalid user found in CHROME_REMOTING_USERS: ${user}"
				ret=1
			fi
		done
	fi
	return ${ret}
}

for_users() {
	local user ret msg log
	msg=$1; shift

	for user in ${CHROME_REMOTING_USERS} ; do
		ebegin "${msg} ${SVCNAME} for ${user}"

		# We need to background the app as it won't fork until the network
		# (including DNS) is available.
		start-stop-daemon \
			-b \
			-u "${user}" \
			-x "${CRD}" \
			-- \
			${OPTIONS} \
			"$@"
		eend $?
		: $(( ret |= $? ))
	done

	return ${ret}
}

start() {
	checkconfig || return
	for_users Starting --start
}

stop() {
	for_users Stopping --stop
}

reload() {
	for_users Reloading --reload
}
