#!/bin/bash

isDisplayLinkConnected() {
    cat /sys/bus/usb/devices/*/idVendor 2> /dev/null | grep -q 17e9
}

if ! isDisplayLinkConnected; then
    if [ "$1" != "check" ]; then
        echo "Displaylink dock not connected" >&2
    fi
    exit 10
fi

for pid in $(pgrep -u $USER); do
    [ -r /proc/$pid/environ ] || continue
    [ "$DISPLAY" ] || export DISPLAY=$(tr '\0' '\n' < /proc/$pid/environ | grep "^DISPLAY=" | cut -d = -f 2-)
    [ "$XAUTHORITY" ] || export XAUTHORITY=$(tr '\0' '\n' < /proc/$pid/environ | grep "^XAUTHORITY=" | cut -d = -f 2-)
    [ "$XDG_CONFIG_HOME" ] || export XDG_CONFIG_HOME=$(tr '\0' '\n' < /proc/$pid/environ | grep "^XDG_CONFIG_HOME=" | cut -d = -f 2-)

    [ "$DISPLAY" -a "$XAUTHORITY" -a "$XDG_CONFIG_HOME" ] && break
done

[ "$XDG_CONFIG_HOME" ] || export XDG_CONFIG_HOME="$HOME/.config"

if [ -z "$DISPLAY" ]; then
    if [ "$1" != "check" ]; then
        echo "User $USER don't use X11" >&2
    fi
    exit 11
fi

[ "$1" == "check" ] && exit 0

echo "Finding modesetting providers"
xrandr --listproviders | awk '$1 == "Provider" && $NF ~ /modesetting$/ && /Sink Output/ {gsub(/:/, "", $2); print $2}' |\
while read providerId; do
    [ "$providerId" = "0" ] && continue
    xrandr --setprovideroutputsource "$providerId" 0
    sleep 0.5
done

CONFIG_PATH="$XDG_CONFIG_HOME/displaylink-connect.conf"
[ -r "$CONFIG_PATH" ] && . "$CONFIG_PATH"

if [ "$DISABLE_MONITOR_SETTING" != "1" ]; then
    [ ${#DISPLAYLINK_MONITORS[@]} -ne 0 ] || DISPLAYLINK_MONITORS=( $(xrandr | awk '$2 == "connected" && $1 ~ /DVI-I-[0-9]-[0-9]/ { print $1 }' | sort -k 4 -t "-" ) )
    [ "$MAIN_MONITOR" ] || MAIN_MONITOR=$(xrandr | awk '$2 == "connected" && $1 !~ /DVI-I-[0-9]-[0-9]/ { print $1; exit }')

    xrandr --output "$MAIN_MONITOR" --auto --primary
    prevMonitor="$MAIN_MONITOR"

    if [ "$MIRROR_MAIN_MONITOR" = "1" ]; then
        [ "$MIRROR_MONITOR" ] || MIRROR_MONITOR="${DISPLAYLINK_MONITORS[0]}"
        DISPLAYLINK_MONITORS=( ${DISPLAYLINK_MONITORS[@]/$MIRROR_MONITOR} )

        xrandr --output "$MIRROR_MONITOR" --auto --same-as "$MAIN_MONITOR"
        prevMonitor="$MIRROR_MONITOR"
    fi

    for currMonitor in ${DISPLAYLINK_MONITORS[@]}; do
        xrandr --output "$currMonitor" --auto --right-of "$prevMonitor"
        prevMonitor="$currMonitor"
    done
fi
