#!/bin/bash

. /etc/default/locale

TEXTDOMAIN=switch_monitor

LAPTOP_ONLY_STRING=$"Laptop display only"
EXTERNAL_ONLY_STRING=$"External monitor only"
EXTEND_MODE_STRING=$"Extend display"
MIRROR_MODE_STRING=$"Mirror displays"

PACKAGE_NAME="oem-superkey-workaround"
PACKAGE_PATH="/usr/share/$PACKAGE_NAME"
PACKAGE_ICONPATH="$PACKAGE_PATH/icons/"

LAPTOP_ONLY_PIC="-h string:image_path:$PACKAGE_ICONPATH/notification-laptop-display-only.svg"
EXTERNAL_ONLY_PIC="-h string:image_path:$PACKAGE_ICONPATH/notification-external-display-only.svg"
EXTEND_MODE_PIC="-h string:image_path:$PACKAGE_ICONPATH/notification-extend-display.svg"
MIRROR_MODE_PIC="-h string:image_path:$PACKAGE_ICONPATH/notification-mirrored-display.svg"

#NotifyOSD synchronous command
OSDSYNC_ENABLED="-h string:x-canonical-private-synchronous:1"

detect_display_mode()
{
    local connected_str connected displays connected_adapter
    connected_str=$(xrandr|grep ' connected '| grep '+[0-9]*')
    connected=$(echo $connected_str | tr ' ' '\n' | grep -c '+[0-9]*')

    if [ "$connected" = "1" ]
    then
        connected_adapter=$(echo $connected_str | tr ' ' '\n' | grep -E "eDP|LVDS")
        case "$connected_adapter" in
        eDP*|LVDS*)
            DISPLAY_MODE=$LAPTOP_ONLY_STRING
            DISPLAY_PIC=$LAPTOP_ONLY_PIC
            ;;
        *)
            DISPLAY_MODE=$EXTERNAL_ONLY_STRING
            DISPLAY_PIC=$EXTERNAL_ONLY_PIC
            ;;
        esac  
    else
        displays=$(echo $connected_str | tr ' ' '\n' | grep -c '+0+0')
        if [ "$displays" = "1" ]
        then
            DISPLAY_MODE=$EXTEND_MODE_STRING
            DISPLAY_PIC=$EXTEND_MODE_PIC
        else
            DISPLAY_MODE=$MIRROR_MODE_STRING
            DISPLAY_PIC=$MIRROR_MODE_PIC
        fi
    fi
}

# sync the monitor status workaround (LP: #1093417)
xrandr

# call gnome-settings-dameon xrandr plugin for handing video mode switch
# the only parameter is timestamp, I use 0 here because g-s-d ignore it anyway. 

dbus-send --session --print-reply \
  --dest=org.gnome.SettingsDaemon \
  /org/gnome/SettingsDaemon/XRANDR \
  org.gnome.SettingsDaemon.XRANDR_2.VideoModeSwitch int64:0

xrandr --noprimary

sleep 1

detect_display_mode

notify-send "$DISPLAY_MODE" $DISPLAY_PIC $OSDSYNC_ENABLED
