#!/bin/bash
#Проверяем установлен ли Xinput-calibrator и, если нет, устанавливаем его
if ! which xinput_calibrator > /dev/null; then
    sudo apt -y install xinput-calibrator
fi

#Поворот основного экрана
rotate=$(xrandr | grep -E "1080x1920\+|2160x3840\+" | awk -F '(' '{print $1}' | awk '{ print $NF }')
echo "rotate=$rotate"
#Порт основного экрана
primary_id=$(xinput_calibrator --list | grep -Pi 'touch|ilitek' | grep -ive 'mouse\|keyboard' | grep -Po 'id=\K[0-9]+')
echo "primary_id=$primary_id"

#Калибруем основной экран
case $rotate in
    left)
    xinput set-prop $primary_id "Coordinate Transformation Matrix" 0 -1 1 1 0 0 0 0 1
    ;;
    right)
    xinput set-prop $primary_id "Coordinate Transformation Matrix" 0 1 0 -1 0 1 0 0 1
    ;;
esac

#Если экранов с тач-устройствами 2, привязывает тач-устройства к экранам
if [[ $(xrandr | grep " connected" | wc -l) -eq 2 ]]
    then
	primary_port=$(xrandr | grep -E "1080x1920\+|2160x3840\+" | awk '{print $1;}')
	secondary_port=$(xrandr | grep -E " connected" | grep -ive 'primary' | awk '{print $1;}')
	secondary_id=$(xinput_calibrator --list | grep -ive 'touch\|ilitek\|mouse\|keyboard' | grep -Po 'id=\K[0-9]+')
	echo -e "primary_port=$primary_port\nsecondary_id=$secondary_id\nsecondary_port=$secondary_port"
	xinput map-to-output $primary_id $primary_port
	xinput map-to-output $secondary_id $secondary_port
fi