#!/bin/bash

# @post: $SCREEN variable and $DEVICES array are set
source /etc/de-1st-rotate/config.cfg || exit $?

if [ "$#" -ne "1" ]; then
  echo "usage: $0 ORIENTATION";
  exit 1;
fi

ORIENTATION="$1"

# "xrandr ... || exit 1" does not work to check if $SCREEN exists.
# if e.g. the given output "$SCREEN" does not exist.
# Thus we check if $SCREEN is valid with grep:
xrandr --listmonitors | grep --quiet "\s${SCREEN}\$" || {
  echo "The given screen ${SCREEN} does not exist.";
  exit 1;
}

xrandr --output "${SCREEN}" --rotate "${ORIENTATION}" || {
  echo "Could not rotate ${SCREEN}!";
  exit 1;
}

for i in "${DEVICES[@]}"; do
  xinput --map-to-output "${i}" "${SCREEN}" || {
    echo "Could not map device ${i} to screen ${SCREEN}!";
    FAILURE=true
  }
done

if [ "${FAILURE}" = "true" ]; then
  # At least one error occurred.
  exit 1;
fi