#!/bin/bash

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

if [ "$#" -gt "1  " ] || [ "${1}" = "-h" ] || [ "${1}" = "--help" ] ; then
  echo "usage:
- Manually specify orientation:
  ${0} ORIENTATION
- Automatically detect orientation:
  ${0}" >&2;
  exit 1;
fi

if [ -z "${1}" ]; then
  ORIENTATION="$(/usr/lib/de-p1st-rotate/get-orientation)" || exit $?;
else
  ORIENTATION="$1"
fi

# "xrandr ... || exit 1" does not work to check if $SCREEN exists,
# e.g. if 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." >&2;
  exit 1;
}

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

for i in "${DEVICES[@]}"; do
  xinput --map-to-output "${i}" "${SCREEN}" || {
    echo "Could not map device ${i} to screen ${SCREEN}! Please check output of 'xinput'." >&2;
    FAILURE=true
  }
done

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