#!/bin/bash
#
# $VGA_DEVICE toggle
# Andrew Wyatt
# Tool to enable / disable $VGA_DEVICE output

JUPITER_PATH="/usr/lib/jupiter/scripts"
JUPITER_VAR="/var/jupiter"

if [[ "$*" =~ "silent" ]]; then
  NO_NOTIFY=1
fi

. $JUPITER_PATH/notify

NICON="/usr/share/pixmaps/jupiter/display.png"

if [ ! -d "$JUPITER_VAR" ]; then
  mkdir $JUPITER_VAR 2>/dev/null
fi

if [ -e "$JUPITER_VAR/vga_saved" ]; then
  VGA_RESTORE=$(cat $JUPITER_VAR/vga_saved)
fi

LVDS_DEVICE=$(xrandr | grep " connected" | awk '{print $1}' | grep LVDS)
VGA_DEVICE=$(xrandr | grep " connected" | awk '{print $1}' | grep "VGA\|DVI\|DP")
VGA_XRANDR=$(xrandr)
VGA_STATUS=$(echo "$VGA_XRANDR" | grep 'VGA.*\|DVI.*\|DP.* connected' >/dev/null 2>&1 && echo connected)
VGA_ENABLED=$(echo "$VGA_XRANDR" | grep 'VGA.*\|DVI.*\|DP.* connected' -A 1 | grep "\*" >/dev/null 2>&1 && echo 1)

function video_toggle {
  if [ "$VGA_RESTORE" = "lvds" ]; then
    vga
  elif [ "$VGA_RESTORE" = "vga" ]; then
    clone
  else
    lvds
  fi
}

function vga {
  if [ ! "$VGA_STATUS" = "connected" ]; then
      notify $"External monitor not detected." $NICON
      exit 0
  fi
  xrandr --output $VGA_DEVICE --auto
  if [ "$?" = "0" ]; then
    xrandr --output $LVDS_DEVICE --off
    notify $"External Display Mode" $NICON
    echo vga > $JUPITER_VAR/vga_saved
    $JUPITER_PATH/resolutions modes
  else
    notify $"Could not enable monitor." $NICON
  fi
  exit 0
}

function clone {
  if [ ! "$VGA_STATUS" = "connected" ]; then
      notify $"External monitor not detected." $NICON
      exit 0
  fi
  xrandr --output $VGA_DEVICE --auto
  if [ "$?" = "0" ]; then
    xrandr --output $LVDS_DEVICE --auto
    notify $"Clone Display Mode" $NICON
    echo clone > $JUPITER_VAR/vga_saved
    $JUPITER_PATH/resolutions modes
  else
    notify $"Could not enable monitor." $NICON
  fi
  exit 0
}

function lvds {
  xrandr --output $LVDS_DEVICE --auto
  if [ "$?" = "0" ]; then
    xrandr --output $VGA_DEVICE --off
    notify $"Internal Display Mode" $NICON
    echo lvds > $JUPITER_VAR/vga_saved
    $JUPITER_PATH/resolutions modes
  else
    notify "Could not enable monitor." $NICON
  fi
  exit 0 
}

case $1 in
  restore)
    NO_NOTIFY=1
    $VGA_RESTORE
  ;;
  clone)
    clone
  ;;
  vga)
    vga
  ;;
  lvds)
    lvds
  ;;
  *)
    video_toggle
  ;;
esac
