#!/bin/sh

if [ -n "$(command -v pkexec)" ]; then
	xhost_set=false
	if [ "$XDG_SESSION_TYPE" = "wayland" ] && [ -n "$(command -v xhost)" ] && ! xhost | grep -q 'SI:localuser:root\|LOCAL:'; then
		xhost si:localuser:root
		xhost_set=true
	fi

	if pkaction --action-id org.pkexec.cpu-x > /dev/null 2>&1 && command -v cpu-x | grep -qv "/tmp/.mount_CPU-X" ; then
		# CPU-X is installed on system
		pkexec --disable-internal-agent "/usr/bin/cpu-x" "$@"
	else
		# CPU-X is executed from AppImage
		pkexec --disable-internal-agent env DISPLAY="$DISPLAY" XAUTHORITY="$XAUTHORITY" "/usr/bin/cpu-x" "$@"
	fi

	status=$?
	if [ $status -eq 126 ] || [ $status -eq 127 ]; then
		"/usr/bin/cpu-x" "$@"
	fi

	if $xhost_set; then
		xhost -si:localuser:root
	fi
else
	"/usr/bin/cpu-x" "$@"
fi
