#!/bin/sh

# xrandr.sh
# 2013-05-11
# by Gernot Walzl

# This script uses xrandr to easily enable an external monitor.
# It works with intel and radeon cards.
# Inspired by
# http://www.thinkwiki.org/wiki/Sample_Fn-F7_script

STATE=$(xrandr --query | grep " connected " | sed 's/(.*//g')
INTERNAL=$(echo "$STATE" | grep "LVDS" | cut -d' ' -f1)
EXTERNAL=$(echo "$STATE" | grep "VGA" | cut -d' ' -f1)

print_usage () {
  echo "${0} {list|primary|secondary|clone|extend|toggle}"
}

list () {
  echo "$STATE"
}

primary () {
  xrandr --output "$EXTERNAL" --off
  xrandr --output "$INTERNAL" --auto
}

secondary () {
  if [ -z "$EXTERNAL" ]; then
    return 1
  fi
  xrandr --output "$INTERNAL" --off
  xrandr --output "$EXTERNAL" --auto
}

clone () {
  if [ -z "$EXTERNAL" ]; then
    return 1
  fi
  local MODE="1024x768"
  xrandr --output "$EXTERNAL" --off
  xrandr --output "$INTERNAL" --mode "$MODE"
  xrandr --output "$EXTERNAL" --mode "$MODE" --same-as "$INTERNAL"
}

extend () {
  if [ -z "$EXTERNAL" ]; then
    return 1
  fi
  xrandr --output "$EXTERNAL" --off
  xrandr --output "$INTERNAL" --auto
  xrandr --output "$EXTERNAL" --auto --right-of "$INTERNAL"
}

toggle () {
  if [ -z "$EXTERNAL" ]; then
    primary
    return 1
  fi
  local INTERNAL_STATE=$(echo "$STATE" | grep "$INTERNAL" | sed 's/.*connected[ ]*//')
  local EXTERNAL_STATE=$(echo "$STATE" | grep "$EXTERNAL" | sed 's/.*connected[ ]*//')
  local CURRENT=""
  if [ -z "$EXTERNAL_STATE" ]; then
    CURRENT="primary"
  elif [ -z "$INTERNAL_STATE" ]; then
    CURRENT="secondary"
  elif [ "$INTERNAL_STATE" = "$EXTERNAL_STATE" ]; then
    CURRENT="clone"
  else
    CURRENT="extend"
  fi
  case "$CURRENT" in
    primary) secondary ;;
    secondary) clone ;;
    clone) extend ;;
    extend) primary ;;
  esac
}

case "$1" in
  list) list ;;
  primary) primary ;;
  secondary) secondary ;;
  clone) clone ;;
  extend) extend ;;
  toggle) toggle ;;
  *) print_usage ;;
esac