#!/bin/sh

DISPMANAGE_EXT_PORT_ID_PREFIX="DisplayPort"
DISPMANAGE_LAPTOP_ID="eDP"
DISPMANAGE_LAPTOP_MODE='"1920x1280_60.00"'

non_primary_monitors_off() {
    xrandr |
        grep -v "^Screen" |
        grep -v "^\s" |
        grep -v "primary" |
        while read -r target_mon_id remaining_text; do
            xrandr --output "$target_mon_id" --off
        done
}

solo_monitor_mode() {
    mode_id="--auto"
    [ "$1" = "$DISPMANAGE_LAPTOP_ID" ] &&
        [ -n "$DISPMANAGE_LAPTOP_MODE" ] &&
        mode_id="--mode $DISPMANAGE_LAPTOP_MODE"
    echo "$mode_id" | xargs xrandr --output "$1" --primary
    non_primary_monitors_off
    ! [ "$2" = "--quiet" ] && echo "display-manage: solo monitor mode, $1"
}

primary_mon_id=""
case "$1" in
    (l | laptop)
        primary_mon_id="$DISPMANAGE_LAPTOP_ID"
        ;;
    (e | external)
        primary_mon_id=$(
            xrandr |
                grep "^$DISPMANAGE_EXT_PORT_ID_PREFIX.*\sconnected" |
                sed -n "1p" |
                sed -E "s/^([^ ]+).*$/\1/g"
        )
        ;;
    # for one-off/special cases; just set things explicitly here and exit
    # (c1 | case1)
    #     xrandr --output DisplayPort-1 --primary --auto \
    #         --output HDMI-1 --auto \
    #         --output eDP --auto --same-as DisplayPort-1
    #     exit 0
    #     ;;
esac

[ -z "$primary_mon_id" ] &&
    echo "display-manage: target monitor not detected or not configured; using laptop" &&
    solo_monitor_mode "$DISPMANAGE_LAPTOP_ID" &&
    exit 0

case "$2" in
    (m | mirror)
        solo_monitor_mode "$primary_mon_id" --quiet
        xrandr --output "$DISPMANAGE_LAPTOP_ID" --auto --same-as "$primary_mon_id"
        echo "display-manage: $primary_mon_id monitor, primary; laptop monitor, mirror"
        ;;
    (*)
        solo_monitor_mode "$primary_mon_id"
        ;;
esac
