#!/bin/sh
# Process adapter for openSUSE's display-manager-legacy.service.
# SPDX-License-Identifier: GPL-2.0-or-later
# The native plasmalogin.service runs /usr/bin/plasmalogin directly and never
# uses this file.

pidfile=/run/plasmalogin.pid
child_pid=
termination_requested=0
umask 022

remove_own_pidfile() {
    saved_status=$?
    recorded_pid=

    trap - EXIT

    if [ -r "$pidfile" ]; then
        IFS= read -r recorded_pid < "$pidfile" || recorded_pid=
    fi
    if [ "$recorded_pid" = "$$" ]; then
        rm -f "$pidfile"
    fi

    exit "$saved_status"
}

terminate_child() {
    termination_requested=1
    if [ -n "$child_pid" ]; then
        kill -TERM "$child_pid" 2>/dev/null || :
    fi
}

# display-manager-legacy.service has KillMode=process, so its SIGTERM reaches
# this supervisor only.  Forward it to the real daemon and remain alive until
# the daemon has exited.  Ignore HUP as an additional guard for direct callers;
# the dispatcher wrapper turns systemd reload into kill -0 as well.
trap remove_own_pidfile EXIT
trap terminate_child TERM INT QUIT
trap : HUP

if ! printf '%s\n' "$$" >"$pidfile"; then
    exit 1
fi

/usr/bin/plasmalogin "$@" &
child_pid=$!

# A trapped signal may interrupt wait(1) before plasmalogin has completed its
# orderly shutdown.  Keep waiting while the child still exists.
while :; do
    wait "$child_pid"
    child_status=$?
    if ! kill -0 "$child_pid" 2>/dev/null; then
        break
    fi
done

child_pid=
if [ "$termination_requested" -eq 1 ]; then
    child_status=0
fi
exit "$child_status"
