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

# Put the wrappers in front of /usr/bin/hsh*, or take them away again with
# --undo. Installing the package does NOT do this: on a real host hasher works
# without any of it, and shadowing its entry points system-wide is not something
# a package should decide. A container image runs this deliberately.

libexec=/usr/lib/hasher-kayfabe
bindir=/usr/local/bin
profile=/etc/profile.d/hasher-kayfabe.sh
# Every hasher entry point that talks to the daemon. Miss one and a user whose
# first command is that one meets ECONNREFUSED with nothing to start the daemon.
wrapped="hsh hsh-run hsh-shell hsh-rebuild hsh-initroot hsh-install hsh-copy
	 hsh-mkchroot hsh-rmchroot"


[ "$(id -u)" = 0 ] || {
	echo "${0##*/}: must run as root" >&2
	exit 1
}

# Installed twice: as kayfabe-activate and as kayfabe-deactivate, because a
# command whose name says what it does is easier to find than a flag.
mode=${1-}
[ "${0##*/}" = kayfabe-deactivate ] && mode=--undo

# Shadowing /usr/bin/hsh* on a real machine would put a lazily started,
# preloaded daemon in front of the one its init runs. Undoing is allowed
# everywhere, so a system that somehow got activated can always be cleaned up.
if [ "$mode" != --undo ] && ! "$libexec/kayfabe-in-container"; then
	echo "${0##*/}: this is not a container; hasher needs none of this here" >&2
	exit 1
fi

case "$mode" in
--undo)
	# Remove only what points at our wrapper: a hand-made /usr/local/bin/hsh
	# belongs to whoever put it there.
	for n in $wrapped; do
		[ "$(readlink "$bindir/$n" 2>/dev/null)" = "$libexec/kayfabe-wrapper" ] || continue
		rm -f "$bindir/$n"
	done
	cmp -s "$profile" "$libexec/profile.sh" && rm -f "$profile"
	echo "${0##*/}: hasher entry points are back to /usr/bin"
	;;
"")
	[ -e "$libexec/kayfabe-wrapper" ] || {
		echo "${0##*/}: $libexec/kayfabe-wrapper is missing" >&2
		exit 1
	}
	mkdir -p "$bindir"
	for n in $wrapped; do
		# Someone else's file is not ours to replace: --undo would remove
		# only our symlink, and the original would be gone for good.
		if [ -e "$bindir/$n" ] &&
			[ "$(readlink "$bindir/$n" 2>/dev/null)" != "$libexec/kayfabe-wrapper" ]; then
			echo "${0##*/}: $bindir/$n exists and is not ours — leaving it alone" >&2
			continue
		fi
		ln -sf "$libexec/kayfabe-wrapper" "$bindir/$n"
	done
	# ALT's /etc/profile rebuilds PATH with /usr/bin ahead of /usr/local/bin, so
	# a login shell needs this snippet; podman's own default PATH already has
	# the right order. Copied, not linked: that loop takes only regular
	# executable files ([ -x ] and ! [ -L ]), so a symlink here would be
	# silently ignored.
	install -m755 "$libexec/profile.sh" "$profile"
	echo "${0##*/}: hasher entry points now start hasher-privd on demand"
	;;
*)
	echo "usage: kayfabe-activate [--undo], or kayfabe-deactivate" >&2
	exit 2
	;;
esac
