#!/bin/bash
#
# set primary 
# Jochen Schulz
# Tool to set primary display 
set -x
JUPITER_PATH="/usr/lib/jupiter/scripts"
JUPITER_VAR="/var/lib/jupiter"

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

. $JUPITER_PATH/notify

NICON="/usr/share/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\|HDMI")
VGA_XRANDR=$(xrandr)
VGA_STATUS=$(echo "$VGA_XRANDR" | grep 'VGA.*\|DVI.*\|DP.*\|HDMI.* connected' >/dev/null 2>&1 && echo connected)
VGA_ENABLED=$(echo "$VGA_XRANDR" | grep 'VGA.*\|DVI.*\|DP.*\|HDMI.* connected' -A 1 | grep "\*" >/dev/null 2>&1 && echo 1)

function internal {
  xrandr --output $LVDS_DEVICE --primary
  if [ "$?" = "0" ]; then
    notify $"Internal Display Primary" $NICON
    #echo vga > $JUPITER_VAR/vga_saved
  else
    notify $"Could not set enable monitor primary." $NICON
  fi
  exit 0
}

function external {
  if [ ! "$VGA_STATUS" = "connected" ]; then
      notify $"External monitor not detected." $NICON
      exit 0
  fi
  xrandr --output $VGA_DEVICE --primary
  if [ "$?" = "0" ]; then
    notify $"External Display Primary" $NICON
    #echo clone > $JUPITER_VAR/vga_saved
  else
    notify $"Could not set monitor primary." $NICON
  fi
  exit 0
}


case $1 in
  restore)
    NO_NOTIFY=1
    $VGA_RESTORE
  ;;
  internal)
    internal
  ;;
  external)
    external
  ;;
  *)
    internal
  ;;
esac
