#!/bin/bash

dock_hotplug_handle() {
	# Set DISPLAY needed for everything.
	if [ -e "/tmp/.X11-unix/X1" ]; then export DISPLAY=":1"; else export DISPLAY=":0"; fi

	# User name is important for rotation and must always be filled in. Users with pulse are preferred.
	# Try logged-in user.
	export DH_USER_NAME=$(who | awk -v vt="$DISPLAY" '$0 ~ vt {print $1}')
	# Try gdm greeter.
	if [ "$DH_USER_NAME" == "" ]; then export DH_USER_NAME=gdm; fi
	# Nothing was found. Use root to at least let sudo user xrandr commands to succeed.
	# if [ "$DH_USER_NAME" == "" ]; then export DH_USER_NAME=root; fi
	export DH_USER_ID=$(id -u "$DH_USER_NAME")

	# Set pulse server. If user failed to be found then pactl cmds will fail. And it's fine.
	export DH_PULSE_SERVER="unix:/run/user/"$DH_USER_ID"/pulse/native"

	# Set xorg vars.
	export DP_SETTINGS=
	export DSI_SETTINGS="--primary --mode 720x1280 --rotate left --panning 1280x720+0+0 --pos 0x0 --dpi 120 --fb 1280x720"
	export XAUTHORITY=$(ps -C Xorg -f --no-header | sed -n 's/.*-auth //; s/ -[^ ].*//; p')

	# Set DP output vars.
	if [[ "$1" -eq 1 ]]; then
		# Read custom WIDTHxHEIGHT from dock-hotplug.conf.
		if [ -e "/etc/dock-hotplug.conf" ]; then
			export DP_SETTINGS=$(cat /etc/dock-hotplug.conf)
		fi
		# No custom res, set max.
		if [ "$DP_SETTINGS" == "" ]; then
			DP_SETTINGS=$(xrandr -q | sed -E -n '/DP-0/s/.* ([0-9]+x[0-9]+)\+.*/\1/p')
		fi
		# If res found set it, otherwise auto. It's impossible to reach auto, but just in case.
		if [ "$DP_SETTINGS" == "" ]; then
			export DP_SETTINGS="--primary --auto"
		else
			export DP_SETTINGS="--primary --mode "$DP_SETTINGS" --panning "$DP_SETTINGS"+0+0 --pos 0x0 --fb "$DP_SETTINGS""
		fi
	fi

	# Configure Video and Audio. TODO: Don't change audio card profile if headphones, but also keep order.
	if [[ "$1" -eq 1 ]]
	then
		sudo -u "$DH_USER_NAME" pactl --server "$DH_PULSE_SERVER" set-card-profile 1 off
		sudo -u "$DH_USER_NAME" pactl --server "$DH_PULSE_SERVER" set-card-profile 0 output:hdmi-stereo
		sudo -u "$DH_USER_NAME" DISPLAY=":1" xrandr --output DSI-0 --off --output DP-0 $DP_SETTINGS
	  	sudo -u "$DH_USER_NAME" DISPLAY=":0" xrandr --output DSI-0 --off --output DP-0 $DP_SETTINGS
		# Reapply config to avoid X stubbornness.
		sleep 0.2
		DISPLAY=":1" xrandr --output DSI-0 --off --output DP-0 $DP_SETTINGS
		DISPLAY=":0" xrandr --output DSI-0 --off --output DP-0 $DP_SETTINGS
		# On dock touch is still rotated, so we rotate it the same amount.
		xinput set-prop "touchscreen" --type=float "Coordinate Transformation Matrix" 0 -1 1 1 0 0 0 0 1
	else
		sudo -u "$DH_USER_NAME" xinput enable 6 #enable touch screen
		sudo -u "$DH_USER_NAME" pactl --server "$DH_PULSE_SERVER" set-card-profile 1 HiFi
		sudo -u "$DH_USER_NAME" pactl --server "$DH_PULSE_SERVER" set-card-profile 0 off
		sudo -u "$DH_USER_NAME" DISPLAY=":1" xrandr --output DP-0 --off --output DSI-0 $DSI_SETTINGS
		sudo -u "$DH_USER_NAME" DISPLAY=":0" xrandr --output DP-0 --off --output DSI-0 $DSI_SETTINGS
		# Reapply config to avoid X stubbornness.
		sleep 0.2
		DISPLAY=":1" xrandr --output DP-0 --off --output DSI-0 $DSI_SETTINGS
		DISPLAY=":0" xrandr --output DP-0 --off --output DSI-0 $DSI_SETTINGS
	fi

	# Set default scaling and enable always showing cursor.
	if [[ "$1" -eq 0 ]]; then
		gsettings set com.ubuntu.user-interface scale-factor "{'': 8, 'DSI-0': 10, 'DP-0': 8}"
		gsettings set org.gnome.settings-daemon.plugins.cursor active false
	fi

	# Execute custom dock-hotplug.sh.
	# This can override everything. All env vars are passed over because of exporting.
	if [ -e "/etc/dock-hotplug.sh" ]; then
		/bin/bash /etc/dock-hotplug.sh $1
	fi

	sleep 0.8
}

# Main call.
i=1
DP_ENABLED=1
LOOPS=1

# If arg1 is 1 then it's in boot/greeter or DE startup. Loop 5 times for stubborn Greeters/DEs.
if [[ "$1" -eq 1 ]]; then LOOPS=5; fi

# Dock hotplug handler loop. Normally we run it in background. Otherwise when looped we wait for it to finish.
while [ "$i" -le "$LOOPS" ]; do
	if grep -q 1 "/sys/class/switch/dp/state"; then DP_ENABLED=1; else DP_ENABLED=0; fi
	if [[ "$LOOPS" -eq 5 ]]; then
		dock_hotplug_handle $DP_ENABLED
	else
		dock_hotplug_handle $DP_ENABLED & disown
	fi
	i=$(($i + 1))
done

# Set power and fan profiles.
if grep -q 1 "/var/lib/nvpmodel/auto_profiles"; then 
	if [[ "$DP_ENABLED" -eq 1 ]]; then
		nvpmodel -m 0
		nvpmodel -d Console
	else
		nvpmodel -m 1
		nvpmodel -d Handheld
	fi
fi
