#!/bin/bash

# Mouse toggle script for Sway
# Toggles mouse position 60 (MOVE_DISTANCE) pixels upwards on each execution
# Requires ydotool and ydotoold daemon running

# Configuration

MOVE_DISTANCE=66
BOTTOM_MARGIN=190

RANDOM_DELAY_MIN=0
RANDOM_DELAY_MAX=0.25
RANDOM_DELAY=$(awk -v min=$RANDOM_DELAY_MIN -v max=$RANDOM_DELAY_MAX 'BEGIN { srand(); printf "%.2f\n", min + rand() * (max - min) }')
#WL_FIND_CURSOR_BIN="${WL_FIND_CURSOR_BIN:-wl-find-cursor}"
WL_FIND_CURSOR_BIN="/home/raga/repos/linux/wl-find-cursor/wl-find-cursor"

ENABLED_FILE="/tmp/osrs_drop__enabled"
LOCK_FILE="/tmp/osrs_drop__lock"

export YDOTOOL_SOCKET="$HOME/.ydotool_socket"

# Verify dependencies
if ! command -v ydotool &> /dev/null; then
    echo "Error: ydotool is not installed. Install it with: sudo pacman -S ydotool"
    exit 1
fi
if ! command -v bc &> /dev/null; then
    echo "Error: bc is not installed. Install it with: sudo pacman -S bc"
    exit 1
fi
if ! command -v jq &> /dev/null; then
    echo "Error: jq is not installed. Install it with: sudo pacman -S jq"
    exit 1
fi
if ! command -v "$WL_FIND_CURSOR_BIN" &> /dev/null; then
    echo "Error: wl-find-cursor is not installed or not in PATH (looked for '$WL_FIND_CURSOR_BIN')."
    exit 1
fi

# Verify lock file
if [ -f "$LOCK_FILE" ]; then
    echo "Script is already running, skipping..."
    exit 0
fi
echo $$ > "$LOCK_FILE"
trap 'rm -f "$LOCK_FILE"' EXIT

# Check if script should toggle on/off or execute
if [ "$1" = "toggle" ]; then
    if [ -f "$ENABLED_FILE" ]; then
        rm "$ENABLED_FILE"
        echo "Mouse toggle script DISABLED"
    else
        echo "enabled" > "$ENABLED_FILE"
        echo "Mouse toggle script ENABLED"
    fi
    exit 0
fi

# Verify script is enabled
if [ ! -f "$ENABLED_FILE" ]; then
    echo "Mouse toggle script is DISABLED. Use '$0 toggle' to enable."
    exit 0
fi

# Verify ydotoold daemon is running
if ! pgrep -x "ydotoold" > /dev/null; then
    echo "Starting ydotoold daemon..."
    sudo ydotoold &
    sleep 1
fi

CURSOR_POS=$("$WL_FIND_CURSOR_BIN" -p)
if [ -z "$CURSOR_POS" ]; then
    echo "Error: Unable to determine cursor position."
    exit 1
fi
read -r CURSOR_X CURSOR_Y <<< "$CURSOR_POS"

BOTTOM_LIMIT=$(swaymsg -r -t get_outputs | jq --argjson cx "$CURSOR_X" --argjson cy "$CURSOR_Y" --argjson margin "$BOTTOM_MARGIN" '
    .[] | select(.active == true) |
    select($cx >= .rect.x and $cx < (.rect.x + .rect.width) and
            $cy >= .rect.y and $cy < (.rect.y + .rect.height)) |
    (.rect.y + .rect.height - $margin)
' | head -n 1)

if [ -n "$BOTTOM_LIMIT" ]; then
    if [ "$(printf "%.0f" "$CURSOR_Y")" -ge "$(printf "%.0f" "$BOTTOM_LIMIT")" ]; then
        echo "Cursor is already within ${BOTTOM_MARGIN}px of the bottom, skipping move."
        exit 0
    fi
fi

ydotool mousemove -- 0 $MOVE_DISTANCE
