#! /bin/sh
#
# monitors.sh
# Copyright (C) 2017 Fabian Ising <fabian@murgi.de>
#
# Distributed under terms of the Apache v2.0 license.
#

# Get out of town if something errors
set -e

HDMI_STATUS=$(</sys/class/drm/card0/card0-HDMI-A-1/status )  
HDMI2_STATUS=$(</sys/class/drm/card0/card0-HDMI-A-2/status )  
DP_STATUS=$(</sys/class/drm/card0/card0-DP-1/status )  
I3CONFIG=/home/fabian/i3/i3config


echo "Rule run" >> /tmp/udev_test
OUT2="eDP-1"
if [ "connected" == "$HDMI_STATUS" ]; then  
    xrandr >> /tmp/udev_test
    /usr/bin/xrandr --output eDP-1 --auto --left-of HDMI-1
    /usr/bin/notify-send --urgency=low -t 5000 "Graphics Update" "HDMI-1 plugged in"
    echo "HDMI connected" >> /tmp/udev_test
    xrandr >> /tmp/udev_test
    OUT2="HDMI-1"
else  
    /usr/bin/xrandr --output HDMI-1 --off
    /usr/bin/notify-send --urgency=low -t 5000 "Graphics Update" "External monitor (HDMI-1) disconnected"    
    echo "HDMI disconnected" >> /tmp/udev_test
fi

if [ "connected" == "$HDMI2_STATUS" ]; then  
    xrandr >> /tmp/udev_test
    /usr/bin/xrandr --output eDP-1 --auto --left-of HDMI-2
    /usr/bin/notify-send --urgency=low -t 5000 "Graphics Update" "HDMI-2 plugged in"
    echo "HDMI-2 connected" >> /tmp/udev_test
    xrandr >> /tmp/udev_test
    OUT2="HDMI-2"
else  
    /usr/bin/xrandr --output HDMI-2 --off
    /usr/bin/notify-send --urgency=low -t 5000 "Graphics Update" "External monitor (HDMI-2) disconnected"    
    echo "HDMI disconnected" >> /tmp/udev_test
fi

if [ "connected" == "$DP_STATUS" ]; then  
    xrandr >> /tmp/udev_test
    /usr/bin/xrandr --output eDP-1 --auto --right-of DP-1
    /usr/bin/notify-send --urgency=low -t 5000 "Graphics Update" "DP-1 plugged in"
    echo "DP connected" >> /tmp/udev_test
    xrandr >> /tmp/udev_test
    OUT2="DP-1"
else  
    /usr/bin/xrandr --output DP-1 --off
    /usr/bin/notify-send --urgency=low -t 5000 "Graphics Update" "External monitor (DP-1) disconnected"    
    echo "DP disconnected" >> /tmp/udev_test
fi
sed 's/^set\s\s*$OUTPUT_EVEN\s.*/set $OUTPUT_EVEN '$OUT2'/' -i "$I3CONFIG"
i3-msg [workspace=2] move workspace to output $OUT2
i3-msg [workspace=4] move workspace to output $OUT2
i3-msg [workspace=6] move workspace to output $OUT2
i3-msg reload
