#!/bin/bash
#
# display-find.sh - Script to find a specific connected dislay
# and apply configuration settings to it.

# Customize the display to find with the name and model and the 
# first 16 bytes of your display EDID. That's the first line of
# the displays EDID you may find with the shell command: xrandr.
DISPLAY_NAME="Display brand and model name"
DISPLAY_EDID="00ffffffffffff004861000000000000"

# Customize the action to apply to the display
DISPLAY_ACTION=("setting resolution to 1080i" "--mode 1920x1080i")

# Runtime: do not edit the following unless you know what you're doing. :)

# Find connected display outputs
OUTPUTS=($(xrandr | grep " connected" | cut -f 1 -d " "))
OUTPUTS_COUNT=${#OUTPUTS[*]}

# If no connected display is found exit with error
if [ $OUTPUTS_COUNT -eq 0 ]; then
  echo "display-find: error! no display was found, check your cables, exiting..."
  exit 1 # Exit error 1: no displays found
fi

# Echo found connected displays
echo "display-find: found $OUTPUTS_COUNT displays connected at outputs: ${OUTPUTS[*]}"

# Find each connected display's EDID first 16 bytes
OUTPUTS_EDID=($(xrandr --prop | grep -A 1 "EDID:" | cut -f 1 -d "-" | cut -f 2 -d ":"))

# For each found EDID check if matches the display to find then
# apply action and exit, else exit with error
COUNTER=0
for EDID in ${OUTPUTS_EDID[*]}; do
  if [ $EDID == $DISPLAY_EDID ]; then
    DISPLAY_OUTPUT=${OUTPUTS[COUNTER]}
    echo "display-find: found match at $DISPLAY_OUTPUT: $DISPLAY_EDID"
    echo "display-find: found $DISPLAY_NAME"
    echo "display-find: ${DISPLAY_ACTION[0]}"
    sleep 1
    xrandr --output $DISPLAY_OUTPUT ${DISPLAY_ACTION[1]}
    if [ $? -eq 0 ]; then
      echo "display-find: done! exiting..."
      exit 0 # Exit error 0: Ok
    else
      echo "display-find: error! applying settings failed. exiting..."
      exit 2 # Exit error 2: settings failed
    fi
  else
    ((COUNTER++))
    if [ $COUNTER -eq $OUTPUTS_COUNT ]; then
      echo "display-find: sorry, no match found for EDID: $DISPLAY_EDID. exiting..."
      exit 3 # Exit error 3: no match found
    fi
  fi
done
exit 4 # Exit error 4: abnormal error
