#!/usr/bin/env bash

# 1. 缺失的依赖自动安装
if ! command -v xinput &> /dev/null; then
    echo "未找到 xinput 命令，开始安装（sudo apt install -y xinput）..."
    sudo apt update && sudo apt install -y xinput
fi

# 自动获取 DISPLAY 和 XAUTHORITY
if [ -z "$DISPLAY" ] || [ -z "$XAUTHORITY" ]; then
    export $(grep -zE 'DISPLAY|XAUTHORITY' /proc/$(pgrep -u snap gnome-shell | head -n 1)/environ | tr '\0' '\n')
fi

# 检查当前环境是否能运行 xinput
if ! xinput list &> /dev/null; then
    echo "警告: 无法连接到 X 服务 (DISPLAY=$DISPLAY, XAUTHORITY=$XAUTHORITY)"
    exit 1
fi

echo "正在检测触摸设备..."
# 提取名称并过滤
# 提取名称并过滤辅助性设备 (如 UNKNOWN|Mouse)
mapfile -t devices < <(xinput list --short | grep -i "touch" | grep -vE "UNKNOWN|Mouse|Consumer Control" | sed 's/.*↳ \(.*\)id=.*/\1/' | sed 's/[[:space:]]*$//')
if [ ${#devices[@]} -eq 0 ]; then
    read -p "未检测到设备，请手动输入 MatchProduct 名称: " selected_name
else
    echo "可用设备列表："
    for i in "${!devices[@]}"; do echo "  $((i+1))) ${devices[$i]}"; done
    while true; do
        read -p "请选择设备编号 (1-${#devices[@]}): " choice
        selected_name=${devices[$((choice-1))]}
        if [[ -n "$selected_name" && "$choice" =~ ^[0-9]+$ ]]; then
            break
        fi
        echo "无效选择，请重新选择。"
    done
    echo "已选择: $selected_name"
fi

# 3. 选择旋转角度
while true; do
    echo ""
    echo "选择旋转角度："
    echo "1) 正常方向 (0°)"
    echo "2) 顺时针旋转 90°"
    echo "3) 逆时针旋转 -90°"

    read -p "请输入选项 (1-3): " rot_choice

    case $rot_choice in
        1)
            matrix_realtime="1, 0, 0, 0, 1, 0, 0, 0, 1"
            desc="正常方向 (0°)"
            break
            ;;
        2)
            matrix_realtime="0, -1, 1, 1, 0, 0, 0, 0, 1"
            desc="顺时针旋转 90°"
            break
            ;;
        3)
            matrix_realtime="0, 1, 0, -1, 0, 1, 0, 0, 1"
            desc="逆时针旋转 -90°"
            break
            ;;
        *)
            echo "无效的选择，请重新输入。"
            ;;
    esac
done

matrix_conf=$(echo "$matrix_realtime" | tr -d ',' | tr -s ' ')

# 4. 实时生效
echo "正在实时生效: $desc..."
xinput set-prop "$selected_name" "Coordinate Transformation Matrix" $matrix_realtime 2>/dev/null || echo "警告: 实时生效失败。"

# 5. 保存文件
sudo tee /usr/share/X11/xorg.conf.d/99-touchscreen-rotate.conf > /dev/null <<EOF
Section "InputClass"
    Identifier      "Touchscreen Rotation"
    MatchProduct    "$selected_name"
    Option          "TransformationMatrix"  "$matrix_conf"
EndSection
EOF
echo "配置已成功保存！"
