#!/bin/sh
# Usage (as root, normally through pkexec): socket-activate-ctl {start|stop} NAME
# Starts or stops the OpenRC service socket-activate.NAME. stop leaves it running while the
# service it started is still serving a client (for EAC: a game that is still running).
set -eu
action=${1:-}
name=${2:-}
case $action in start|stop) ;; *) echo "usage: socket-activate-ctl {start|stop} NAME" >&2; exit 2 ;; esac
case $name in ''|*[!A-Za-z0-9_.-]*) echo "socket-activate-ctl: invalid name '$name'" >&2; exit 2 ;; esac
svc=socket-activate.$name
[ -e "/etc/init.d/$svc" ] || { echo "socket-activate-ctl: $svc does not exist" >&2; exit 1; }

if [ "$action" = start ]; then
	exec rc-service -N "$svc" start
fi
socket_command=
. "/etc/conf.d/$svc"
if [ -n "$socket_command" ] && pgrep -xf -- "$socket_command" >/dev/null; then
	echo "socket-activate-ctl: ${socket_command%% *} still runs, $svc stays started" >&2
	exit 0
fi
exec rc-service -s "$svc" stop
