#!/bin/sh
# Copyright (c) 2026 Anton Farygin <rider@altlinux.org>
# SPDX-License-Identifier: GPL-2.0-or-later

# Installed under the name of a hasher entry point (hsh, hsh-run, …) somewhere
# ahead of /usr/bin in PATH. Starts hasher-privd on first use, then hands over
# to the real program — so a container that never builds anything never runs a
# daemon.

name=${0##*/}
real=/usr/bin/$name
libexec=/usr/lib/hasher-kayfabe
launcher=/usr/sbin/kayfabe-privd
starter=$libexec/kayfabe-start
socket=/run/hasher-priv/daemon

[ -x "$real" ] || {
	echo "$name: $real is missing — is hasher installed?" >&2
	exit 127
}

# On a host there is an init to start the daemon and nothing for us to do, so
# hand over without a word — whatever hasher does then, including its own error
# message, is what the user would have got without this package installed.
"$libexec/kayfabe-in-container" || exec "$real" "$@"

# "Is the daemon up?" needs both halves, and neither alone is enough: the socket
# file outlives the daemon that created it, so its presence means nothing, while
# the kernel keeps the bound path in /proc/net/unix even after the file is
# unlinked, so a daemon no client can reach still looks alive there.
if ! { [ -S "$socket" ] && grep -q " $socket\$" /proc/net/unix 2>/dev/null; }; then
	# Least privilege first: the setuid helper can do this one thing and
	# nothing else, and only for members of hashman — the test fails silently
	# for everyone else, since a 4710 file is not executable to them. sudo is
	# the fallback for hosts where the helper was disabled.
	if [ -x "$starter" ]; then
		"$starter" || exit
	elif [ "$(id -u)" = 0 ]; then
		"$launcher" || exit
	elif command -v sudo >/dev/null; then
		sudo "$launcher" || exit
	else
		echo "$name: hasher-privd is not running and there is no way to" >&2
		echo "$name: become root — run $launcher as root first." >&2
		exit 1
	fi
fi

exec "$real" "$@"
