#!/bin/dash

# Tags and permissions for seat-related devices: DRM primary/render nodes,
# framebuffers, and evdev (compare systemd 71-seat.rules + 60-seat.hwdb).

. "$VDEV_HELPERS/subr.sh"

# Primary framebuffer or hwdb ID_TAG_MASTER_OF_SEAT (60-seat.hwdb).
seat_fb_is_master() {
	case "$VDEV_PATH" in
	fb0) return 0 ;;
	esac
	if [ -f "$VDEV_METADATA/properties" ]; then
		if /bin/grep -qE '^(ID_TAG_MASTER_OF_SEAT|VDEV_ID_TAG_MASTER_OF_SEAT)=1$' \
		    "$VDEV_METADATA/properties" 2>/dev/null; then
			return 0
		fi
	fi
	return 1
}

main() {

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

	if [ -z "$VDEV_MAJOR" ] || [ -z "$VDEV_MINOR" ]; then
		return 0
	fi

	REAL_DEVNODE="$VDEV_MOUNTPOINT/$VDEV_OS_DEVNAME"

	vdev_add_tag "seat" "$VDEV_METADATA" "$VDEV_GLOBAL_METADATA"
	# udev-compat maps VDEV_SEAT -> E:ID_SEAT (systemd 71-seat.rules)
	vdev_add_property "VDEV_SEAT" "seat0" "$VDEV_METADATA"

	case "$VDEV_OS_DEVNAME" in
	dri/card*)
		vdev_add_tag "master-of-seat" "$VDEV_METADATA" "$VDEV_GLOBAL_METADATA"
		vdev_add_tag "graphics-primary" "$VDEV_METADATA" "$VDEV_GLOBAL_METADATA"
		if [ -e "$REAL_DEVNODE" ]; then
			chgrp video "$REAL_DEVNODE"
			chmod 660 "$REAL_DEVNODE"
		fi
		;;
	dri/renderD*)
		if [ -e "$REAL_DEVNODE" ]; then
			chgrp render "$REAL_DEVNODE" 2>/dev/null || chgrp video "$REAL_DEVNODE"
			chmod 660 "$REAL_DEVNODE"
		fi
		;;
	input/event*)
		if [ -e "$REAL_DEVNODE" ]; then
			chgrp input "$REAL_DEVNODE"
			chmod 660 "$REAL_DEVNODE"
		fi
		;;
	fb*)
		if seat_fb_is_master; then
			vdev_add_tag "master-of-seat" "$VDEV_METADATA" "$VDEV_GLOBAL_METADATA"
		fi
		if [ -e "$REAL_DEVNODE" ]; then
			chgrp video "$REAL_DEVNODE"
			chmod 660 "$REAL_DEVNODE"
		fi
		;;
	snd/card*)
		if [ -e "$REAL_DEVNODE" ]; then
			chgrp audio "$REAL_DEVNODE"
			chmod 660 "$REAL_DEVNODE"
		fi
		;;
	esac

	return 0
}

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