
#!/bin/bash

# Usage: rotate.sh [cw|ccw]
direction="$1"

if [[ "$direction" != "cw" && "$direction" != "ccw" && "$direction" != "0" && "$direction" != "1" && "$direction" != "2" && "$direction" != "3" ]]; then
    echo "Usage: $0 [cw|ccw] OR $0 [0|1|2|3]"

    exit 1
fi

# Get current monitor name
curmon=$(hyprctl monitors | grep -B12 "focused: yes" | head -n1 | awk '{print $2}')
# curmon=$(hyprctl monitors | awk '/focused: yes/{getline; print $2}')

# Get current transform value
# currot=$(hyprctl monitors | awk '/focused: yes/{for(i=0;i<15;i++){getline;if($1=="transform:"){print $2;break}}}')
currot=$(hyprctl monitors | grep -B1 "focused: yes" | head -n1 | awk '{print $2}')

# Calculate new rotation
if [[ "$direction" == "cw" ]]; then
    if [[ "$currot" == "3" ]]; then
        newrot="0"
    else
        newrot=$((currot + 1))
    fi
else # ccw
    if [[ "$currot" == "0" ]]; then
        newrot="3"
    else
        newrot=$((currot - 1))
    fi
fi

if [[ "$direction" == "0" || "$direction" == "1" || "$direction" == "2" || "$direction" == "3" ]]; then
    newrot="$direction"   
fi

echo "Rotating monitor '$curmon' from $currot to $newrot ($direction)"

# Apply new rotation to monitor
hyprctl keyword monitor "$curmon,preferred,auto,1,transform,$newrot"

# Detect touchscreen device name
touchdev=$(hyprctl devices | awk '/Touch Device/{getline; print $1}')

if [[ -n "$touchdev" ]]; then
    echo "Applying same rotation to touchscreen: $touchdev"
    hyprctl keyword "device[$touchdev]:transform" "$newrot"
else
    echo "No touchscreen device detected."
fi

# Reload Eww to adjust bar size
eww reload
