#!/bin/bash

source /etc/monitorctl.conf

INTON="--output $INT --auto"
INTOFF="--output $INT --off"
EXTON="--output $EXT --auto --primary"
EXTOFF="--output $EXT --off"

if xrandr | grep -q "^$EXT connected"; then
	case "$1" in
		ei|ie)
			xrandr $EXTON $INTON --below $EXT
			;;
		e)
			xrandr $INTOFF $EXTON
			;;
		i)
			xrandr $EXTOFF $INTON
			;;
		t)
			OUT=$(xrandr --listactivemonitors)                    # xrandr ausgabe für weitere Analyse speichern
			echo "out: $OUT"
			echo $OUT | grep -q "$INT\$"                    # prüfen, ob interner Monitor überhaupt an
			ON=$?
			echo "on: $ON"
			MONITORS=$(echo $OUT | grep -Po '(?<=Monitors: )\d') # Aktive Bildschirme ermitteln
			echo "monitors: $MONITORS"

			# Internen Monitor nur ausschalten, wenn mindestens noch ein Weiterer aktiv ist
			# sonst steht man plötzlich mit schwarzem Bildschirm da!!!
			if [[ $ON -eq 0 ]]; then
				if [[ "$MONITORS" -ge "2" ]]; then
					xrandr $INTOFF
				fi
			else
				xrandr $INTON --below $EXT
			fi
			;;
		*)
			echo "Usage: monitorctl ei | e | i"
			echo ""
			echo "  ei - external and internal display active"
			echo "  e  - only external display active"
			echo "  i  - only internal display active"
			echo "  t  - toggles state of internal monitor"
			;;
	esac
fi

