#!/usr/bin/bash

# This script fixes the screen orientation in the Desktop Mode in Bazzite-Deck KDE
# Author: d3Xt3r

SYS_ID="$(cat /sys/devices/virtual/dmi/id/product_name)"

STEAM_PID=$(cat $HOME/.steam/steam.pid)
STEAM_CMDLINE_PATH=/proc/$STEAM_PID/cmdline
STEAM_CMDLINE=$(cat $STEAM_CMDLINE_PATH)

IS_GAMEMODE=$(echo $STEAM_CMDLINE | grep gamepadui*)


sleep 1
echo $(date '+%Y-%m-%d %H:%M:%S') Starting Bazzite Desktop Orientation Fix script...| tee -a /tmp/bazrotfix.log

# This bit is needed to allow enough time for the desktop to load, otherwise the fix won't work
# Since Steam launches automatically in the Desktop mode in Bazzite-Deck, we can use it 
# to determine whether or not the desktop has loaded.
while ! pgrep -x "steam" > /dev/null; do
	echo $(date '+%Y-%m-%d %H:%M:%S') Waiting for Steam to start.. | tee -a /tmp/bazrotfix.log
	sleep 0.5
done

sleep 1

# Debug: Get current outputs
kscreen-doctor --outputs 2>&1 | tee -a /tmp/bazrotfix.log

# Fix default scale on for Steam Deck hardware
if /usr/libexec/hardware/valve-hardware; then
	kscreen-doctor output.1.scale.1.00 2>&1 | tee -a /tmp/bazrotfix.log
fi

# Fix desktop orientation
# Rotation options: right, normal, left, inverted
echo $(date '+%Y-%m-%d %H:%M:%S') Fixing desktop orientation... | tee -a /tmp/bazrotfix.log
if [[ ! -z "$IS_GAMEMODE" ]]; then
	kscreen-doctor output.1.rotation.normal 2>&1 | tee -a /tmp/bazrotfix.log
elif [[ ":83E1:Loki Max:AIR Plus:" =~ ":$SYS_ID:" ]]; then
	kscreen-doctor output.1.rotation.left 2>&1 | tee -a /tmp/bazrotfix.log
else
	kscreen-doctor output.1.rotation.normal 2>&1 | tee -a /tmp/bazrotfix.log
fi

echo $(date '+%Y-%m-%d %H:%M:%S') Ending Bazzite Desktop Orientation Fix script >> /tmp/bazrotfix.log
echo -e '\n' >> /tmp/bazrotfix.log
