#!/bin/sh
# Inspired by zexpe's script in LP bug 163877.

# Safe to check output like this, because xrandr isn't translated
OUTPUTS=`xrandr -q | grep ' connected ' | cut -d' ' -f1`
OUTPUTS_ON=`xrandr -q | grep ' connected [^(]' | cut -d' ' -f1`
ARGS=""

ON_LIST=""

# If all or none are on, turn on the first one.
if [ "$OUTPUTS" = "$OUTPUTS_ON" ] || [ -z "$OUTPUTS_ON" ]; then
  ON_LIST=`echo $OUTPUTS | cut -d' ' -f1`
else
  # Some are on, we'll act like only one is on.  If more than one (but not
  # all) are on, the user did something outside of this script.
  # Now, we iterate outputs.
  # If we find one that is on, turn on the next one.
  # If the last output is on, turn on all the outputs.
  FOUND=""
  for o in $OUTPUTS; do
    if [ -z "$FOUND" ]; then
      if echo $OUTPUTS_ON | grep "$o" > /dev/null; then
        FOUND="$o"
      fi
    else
      ON_LIST="$o"
      break
    fi
  done
  
  if [ -z "$ON_LIST" ]; then # last output was on
    ON_LIST="$OUTPUTS"
  fi
fi

for r in $ON_LIST; do
  ARGS="$ARGS --output $r --preferred"
done

# Anything not in the on list is off
for r in $OUTPUTS; do
  if ! echo $ON_LIST | grep "$r" > /dev/null; then
    ARGS="$ARGS --output $r --off"
  fi
done

echo "Running xrandr$ARGS"

xrandr$ARGS

