
#!/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

monitors_json=$(hyprctl monitors -j)

curmon=$(echo "$monitors_json" | jq -r '.[] | select(.focused) | .name')
currot=$(echo "$monitors_json" | jq -r '.[] | select(.focused) | .transform')
curscale=$(echo "$monitors_json" | jq -r '.[] | select(.focused) | .scale')
curwidth=$(echo "$monitors_json" | jq -r '.[] | select(.focused) | .width')
curheight=$(echo "$monitors_json" | jq -r '.[] | select(.focused) | .height')
currefresh=$(echo "$monitors_json" | jq -r '.[] | select(.focused) | .refreshRate | round')
curx=$(echo "$monitors_json" | jq -r '.[] | select(.focused) | .x')
cury=$(echo "$monitors_json" | jq -r '.[] | select(.focused) | .y')

curmode="${curwidth}x${curheight}@${currefresh}"

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

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

# Apply new rotation while preserving current mode and scale
hyprctl eval "hl.monitor({output='$curmon', mode='$curmode', position='${curx}x${cury}', scale=$curscale, transform=$newrot})"

# Detect touchscreen device name
touchdev=$(hyprctl devices -j | jq -r '.touch[0].name // empty')

if [[ -n "$touchdev" ]]; then
    echo "Applying same rotation to touchscreen: $touchdev"
    hyprctl eval "hl.device({name='$touchdev', transform=$newrot})"
else
    echo "No touchscreen device detected."
fi

# Detect pen/tablet device name
pendev=$(hyprctl devices -j | jq -r '.tablets[0].name // empty')

if [[ -n "$pendev" ]]; then
    echo "Applying same rotation to pen/tablet: $pendev"
    hyprctl eval "hl.device({name='$pendev', transform=$newrot, output='$curmon'})"
else
    echo "No pen/tablet device detected."
fi

# Reload Eww to adjust bar size
eww reload
