#!/bin/sh
# Your Name Here - where is again the blog to read about this very cool script?
# Modified by Nico Schottelius, Mon Nov 17 18:26:34 CET 2014

mode="${1:-normal}"
location="${2:-above}"
resolution="${3:-1024x768}"
primary="${4:-$(xrandr | awk '/primary/ { print $1 }')}"


xrandr=$(xrandr)
disconnected=$(echo "$xrandr" | grep disconnected | cut -d' ' -f1)
secondary=$(echo "$xrandr" | grep ' connected' | cut -d' ' -f1 | grep -v $primary)

die_error() {
   echo "[Error] $@" >&2
   exit 1
}

disconnected_off=""
for output in $disconnected; do
	disconnected_off="$disconnected_off --output $output --off"
done

_xrandr() {
   echo "xrandr $disconnected_off $@"
   xrandr $disconnected_off $@
   echo "xrandr return code: $?"
}

case "$mode" in
   beamer)
      [ -n "$secondary" ] || die "No secondary output detected."
      _xrandr --output $primary --mode $resolution --primary \
         --output $secondary --same-as $primary
   ;;
   reset)
      args="--output $primary --auto --primary"
      [ -n "$secondary" ] && args="$args --output $secondary --off"
      _xrandr $args
   ;;
   normal)
      args="--output $primary --auto --primary"
      [ -n "$secondary" ] && args="$args --output $secondary --auto --${location} $primary"
      _xrandr $args
   ;;
   extern)
      if [ -n "$secondary" ]; then
         args="--output $secondary --auto --primary"
         args="$args --output $primary --off"
         _xrandr $args
      else
         echo "No secondary output found, aborting." >&2
         exit 1
      fi
   ;;
esac