#!/bin/bash

# TODO: Am I calling them displays or video outputs? Pick one!
function call_xrandr() {
    xrandr_opts=''

    for output in "${!video_outputs[@]}"; do
        echo "Setting ${output} to ${video_outputs[$output]}"
        xrandr_opts="${xrandr_opts} --output ${output} ${video_outputs[$output]}"
    done

    xrandr $xrandr_opts
}


if [ "$1" = '-a' ]; then
    switch_audio='yes'
    video_mode="$2"
else
    video_mode="$1"
fi

declare -A video_outputs

while read -r display_line; do
    display_name="$(echo "$display_line" | cut -d " " -f 1)"
    video_outputs[$display_name]=' --off'
done <<< "$(xrandr | grep connected)"

# TODO: I'm kind of inattentive, so build in a mechanism to make sure the display I try
#   to use is actually connected.
# TODO: I'm also very lazy, so build a method that automatically figures out which HDMI
#   output to use if there's only one.
case $video_mode in
    'lvds-hdmi1')
        video_outputs['LVDS1']='--primary --mode 1366x768'
        video_outputs['HDMI1']='--mode 1280x720 --above LVDS1'

        if [ "$switch_audio" = 'yes' ]; then
            audio_profile='output:hdmi-stereo'
        fi
        ;;
    'hdmi1')
        video_outputs['HDMI1']='--primary --mode 1280x720'

        if [ "$switch_audio" = 'yes' ]; then
            audio_profile='output:hdmi-stereo'
        fi
        ;;
    'lvds')
        video_outputs['LVDS1']='--primary --mode 1366x768'
        if [ "$switch_audio" = 'yes' ]; then
            audio_profile='output:analog-stereo'
        fi
        ;;

    # This is intended to be a quick rescue mode.
    '') 
        video_outputs['LVDS1']='--primary --mode 1366x768'
        audio_profile='output:analog-stereo'
        ;;
    *)
        echo "No configuration defined for ${video_mode}"
        exit 1
        ;;
esac

call_xrandr "${video_outputs[@]}"
if [ "$switch_audio" = 'yes' ]; then
    ponymix -c 0 set-profile "${audio_profile}"
fi
