#!/bin/sh
set -e
if [ "$1" = configure ]; then
	# The sudoers drop-in must parse, or it would break sudo for everyone
	if ! visudo -cf /etc/sudoers.d/ps3-desktop >/dev/null; then
		echo "ps3-desktop: /etc/sudoers.d/ps3-desktop does not parse: removed" >&2
		rm -f /etc/sudoers.d/ps3-desktop
	fi
	# Any console user may start X; the legacy wrapper runs it with root rights (KMS, input)
	echo "xserver-xorg-legacy xserver-xorg-legacy/xwrapper/allowed_users select anybody" | debconf-set-selections
	if [ -e /etc/X11/Xwrapper.config ]; then
		sed -i 's/^allowed_users=.*/allowed_users=anybody/' /etc/X11/Xwrapper.config
		grep -q '^needs_root_rights=' /etc/X11/Xwrapper.config &&
			sed -i 's/^needs_root_rights=.*/needs_root_rights=yes/' /etc/X11/Xwrapper.config ||
			echo needs_root_rights=yes >> /etc/X11/Xwrapper.config
	else
		printf 'allowed_users=anybody\nneeds_root_rights=yes\n' > /etc/X11/Xwrapper.config
	fi
	# the optical drive's udev rule on the running system too (a disc already in gets its new flags)
	if [ -d /run/udev ] && command -v udevadm >/dev/null; then
		udevadm control --reload 2>/dev/null || true
		udevadm trigger --action=change --subsystem-match=block --sysname-match='sr[0-9]*' 2>/dev/null || true
	fi
	# ps3_game_prefetch.py's byte code, so ps3-game-prefetch imports it instead of compiling it
	# (its game watcher would cost ~5 MB more); again with every python3 (runtime.d hook)
	if command -v py3compile >/dev/null 2>&1; then
		py3compile -p ps3-desktop /usr/lib/ps3/desktop
	else
		python3 -m compileall -q /usr/lib/ps3/desktop >/dev/null 2>&1 || true
	fi
	# the games' own menu entries this package diverted before 0.893 are ps3-games-integration's: its
	# preinst takes each one over; one still held here means it isn't installed (yet), so the entry is
	# given back (the game's own menu entry returns) until it comes and diverts it again
	held=$(dpkg-divert --list | sed -n 's/^diversion of \(.*\) to .* by ps3-desktop$/\1/p')
	for f in $held; do
		case $f in /usr/share/gvfs/remote-volume-monitors/*) continue ;; esac
		dpkg-divert --quiet --package ps3-desktop --rename --remove "$f" ||
			echo "ps3-desktop: could not give back the diversion of $f" >&2
	done
	rmdir /usr/share/ps3-desktop/diverted-menu /usr/share/ps3-desktop 2>/dev/null || true
	# RAM: blueman's privileged helper only on demand (first install only)
	if [ -z "$2" ]; then
		deb-systemd-helper disable blueman-mechanism.service >/dev/null 2>&1 || true
	fi
fi
#DEBHELPER#
exit 0
