#!/bin/dash
# Emulate elogind-uaccess-command for snd/* (udev 73-seat-late.rules).
# Grants rw ACL on the device node to the active session user on the seat.

. "$VDEV_HELPERS/subr.sh"

audio_acl_seat() {
	local _seat

	if [ -f "$VDEV_METADATA/properties" ]; then
		_seat=$(/bin/grep '^VDEV_SEAT=' "$VDEV_METADATA/properties" 2>/dev/null | \
		    /bin/tail -1 | /bin/sed 's/^VDEV_SEAT=//')
		if [ -n "$_seat" ]; then
			echo "$_seat"
			return 0
		fi
	fi

	echo "seat0"
}

audio_acl_apply() {
	local _seat _dev _sid _user

	_seat="$1"
	_dev="$2"

	if [ -z "$_dev" ] || ! [ -e "$_dev" ]; then
		return 0
	fi

	if ! [ -x /usr/bin/setfacl ]; then
		vdev_warn "audio-acl: setfacl not installed (acl package)"
		return 0
	fi

	if ! [ -x /usr/bin/loginctl ]; then
		vdev_warn "audio-acl: loginctl not found"
		return 0
	fi

	_sid=$(/usr/bin/loginctl show-seat "$_seat" -p ActiveSession --value 2>/dev/null)
	if [ -z "$_sid" ] || [ "$_sid" = "0" ]; then
		return 0
	fi

	_user=$(/usr/bin/loginctl show-session "$_sid" -p Name --value 2>/dev/null)
	if [ -z "$_user" ]; then
		vdev_warn "audio-acl: no active user on seat $_seat"
		return 0
	fi

	/usr/bin/setfacl -m "u:$_user:rw" "$_dev" 2>/dev/null || \
	    vdev_warn "audio-acl: setfacl u:$_user:rw $_dev failed"
	return 0
}

main() {
	local _real _seat

	if [ "$VDEV_ACTION" = "remove" ]; then
		return 0
	fi

	if [ "$VDEV_ACTION" != "add" ] && [ "$VDEV_ACTION" != "change" ]; then
		return 0
	fi

	case "$VDEV_PATH" in
	snd/*) ;;
	*) return 0 ;;
	esac

	if [ -z "$VDEV_PATH" ] || [ -z "$VDEV_MOUNTPOINT" ]; then
		return 0
	fi

	_real="$VDEV_MOUNTPOINT/$VDEV_PATH"
	_seat="$(audio_acl_seat)"
	audio_acl_apply "$_seat" "$_real"
	return 0
}

if [ "${VDEV_DAEMONLET:-0}" -eq 0 ]; then
	main
	exit $?
fi
