#!/bin/sh
# Rotate Switch X11 displays and their touch devices together.
# Copyright 2018 Don Bowman; Switch integration contributors.
# Licensed under Apache License, Version 2.0.
export DISPLAY=${DISPLAY:-:0}

apply_orientation() {
    case "$1" in normal|bottom-up|right-up|left-up) ;; *) return 0 ;; esac
    outputs=$(xrandr --current) || return 1
    # Leave docked display configuration to the dock handler.
    [ "$(printf '%s\n' "$outputs" | awk '$2 == "connected" {n++} END {print n+0}')" -eq 1 ] || return 0
    panel=$(printf '%s\n' "$outputs" | awk '$1 ~ /^DSI-/ && $2 == "connected" {print $1; exit}')
    [ -n "$panel" ] || return 0
    mode=$(printf '%s\n' "$outputs" | awk -v panel="$panel" '
        $1 == panel {inside=1; next}
        /^[^[:space:]]/ {inside=0}
        inside && $1 ~ /^[0-9]+x[0-9]+$/ {
            if (!first) first=$1
            if ($0 ~ /\+/) {print $1; found=1; exit}
        }
        END {if (!found) print first}')
    width=${mode%x*}
    height=${mode#*x}
    case "$width:$height" in *[!0-9:]*|:|*:|:*) return 1 ;; esac

    # 4.9 exposes a landscape mode; mainline exposes the portrait panel mode.
    if [ "$width" -ge "$height" ]; then
        case "$1" in
            normal) rotation=normal ;;
            bottom-up) rotation=inverted ;;
            right-up) rotation=right ;;
            left-up) rotation=left ;;
        esac
    else
        case "$1" in
            normal) rotation=left ;;
            bottom-up) rotation=right ;;
            right-up) rotation=normal ;;
            left-up) rotation=inverted ;;
        esac
    fi
    xrandr --output "$panel" --rotate "$rotation" || return 1
    # These are the same output transforms used by KDE's touch mapper.
    # Sensor calibration belongs in libinput, not in a second rotation here.
    case "$rotation" in
        normal) set -- 1 0 0 0 1 0 0 0 1 ;;
        inverted) set -- -1 0 1 0 -1 1 0 0 1 ;;
        right) set -- 0 1 0 -1 0 1 0 0 1 ;;
        left) set -- 0 -1 1 1 0 0 0 0 1 ;;
    esac
    for name in touchscreen stmfts; do
        device=$(xinput list --id-only "$name" 2>/dev/null) || continue
        xinput set-prop "$device" 'Coordinate Transformation Matrix' "$@" || return 1
    done
}

if [ "$#" -gt 0 ]; then
    [ "$#" -eq 2 ] && [ "$1" = --once ] || exit 2
    apply_orientation "$2"
    exit $?
fi

# Process the initial orientation as well as subsequent changes.
monitor-sensor | awk '
    /Accelerometer orientation changed:/ {print $NF; fflush(); next}
    /Has accelerometer \(orientation:/ {
        sub(/^.*orientation: /, ""); sub(/\).*$/, ""); print; fflush()
    }' | while IFS= read -r orientation; do
    apply_orientation "$orientation"
done
