#!/bin/dash

. "$VDEV_HELPERS/subr.sh"

uaccess_seat_id() {
	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"
}

uaccess_apply_elogind() {
	local _cmd _real

	_real="$1"

	# elogind 255.x parse_argv() accepts exactly one positional argument
	# (device node path). A second [SEAT] arg triggers "Usage: … DEVPATH [SEAT]"
	# on every call; seat defaults to seat0 inside the binary when omitted.
	for _cmd in /usr/libexec/elogind-uaccess-command \
	    /lib/elogind/elogind-uaccess-command; do
		if [ -x "$_cmd" ]; then
			"$_cmd" "$_real" 2>/dev/null || \
			    vdev_warn "uaccess: $_cmd $_real failed"
			break
		fi
	done

	return 0
}

main() {

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

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

	if [ -z "$VDEV_MAJOR" ] || [ -z "$VDEV_MINOR" ]; then 
		# can't make a device ID 
		return 0
	fi

	REAL_DEVNODE="$VDEV_MOUNTPOINT/$VDEV_PATH"
	_SEAT="$(uaccess_seat_id)"

    vdev_add_tag "uaccess" "$VDEV_METADATA" "$VDEV_GLOBAL_METADATA"
    vdev_add_property "VDEV_SEAT" "$_SEAT" "$VDEV_METADATA"
    
    # Grouping by device type
    case "$VDEV_PATH" in
        audio*|snd/*|dsp*)
            [ -e "$REAL_DEVNODE" ] && chgrp audio "$REAL_DEVNODE" ;;
        video*|dri/*)
            chgrp video "$REAL_DEVNODE" ;;
        hidraw*|usb/lp*)
            chgrp plugdev "$REAL_DEVNODE" ;;
        input/event*)
            chgrp input "$REAL_DEVNODE" ;;
    esac

    [ -e "$REAL_DEVNODE" ] && chmod 660 "$REAL_DEVNODE"

	# elogind 73-seat-late.rules: RUN+=elogind-uaccess-command (eudev uaccess builtin)
	if [ -e "$REAL_DEVNODE" ]; then
		uaccess_apply_elogind "$REAL_DEVNODE"
		case "$VDEV_PATH" in
		snd/*)
			# vdev has no udev RUN hook; audio-acl.sh mirrors elogind-uaccess-command
			if [ -x "$VDEV_HELPERS/audio-acl.sh" ]; then
				"$VDEV_HELPERS/audio-acl.sh"
			fi
			;;
		esac
	fi
}

if [ $VDEV_DAEMONLET -eq 0 ]; then 
	main 
	exit $?
fi
