#!/bin/bash

REFERENCE_MONITOR="$(xrandr | awk 'BEGIN { min_height = 0 } /^[a-zA-Z0-9-]+ connected/ { match($0, "([0-9]+)x[0-9]+", monitor_height); if (min_height == 0 || min_height > monitor_height[1]) { min_height = monitor_height[1]; monitor=$1 } } END { print monitor }')"
MONITOR_RESULUTION="$(xrandr | awk 'BEGIN { min_height = 0 } /^[a-zA-Z0-9-]+ connected/ { match($0, "([0-9]+)x[0-9]+", monitor_height); if (min_height == 0 || min_height > monitor_height[1]) { min_height = monitor_height[1]; monitor_resolution=monitor_height[0] } } END { print monitor_resolution }')"

echo "Reference monitor:" "$REFERENCE_MONITOR" "$MONITOR_RESULUTION"

get_best_common_mode() {
	xrandr | awk -e '
	# Reset current monitor
	/^[a-zA-Z0-9-]/ {
		current_monitor=""
	}

	# Set monitor if it is connected
	/^[a-zA-Z0-9-]+ connected/ {
		current_monitor=$1
		active_monitors += 1
	}

	# Filter for some kind of resolution
	/^   [0-9]+x[0-9]+/ && current_monitor != "" {
		available_modes[$1] += 1
	}

	END {
		i = 0
		for (mode in available_modes) {
			match(mode, "([0-9]+)x([0-9]+)", resolution)
			pixels = resolution[1]*resolution[2]
			mode_pixels_list[i] = pixels
			mode_pixels[pixels] = mode
			i++
		}
		asort(mode_pixels_list)
		for (n = active_monitors; n > 0; n--) {
			for (i = length(mode_pixels_list)-1; i >= 0 ; i--) {
				mode = mode_pixels[mode_pixels_list[i]]
				if (available_modes[mode] >= n) {
					print mode
					exit
				}
			}
		}
	}'
}

case "$1" in
	mirror)
		BEST_COMMON_MODE="$(get_best_common_mode)"
		xrandr --output "$REFERENCE_MONITOR" --primary
		xrandr | awk '/^[a-zA-Z0-9-]+ connected/ { print $1 }' | while read monitor; do
			if [[ -n "$BEST_COMMON_MODE" ]] ; then
				echo "Setting mode $BEST_COMMON_MODE for $monitor"
				xrandr --output "$monitor" --mode "$BEST_COMMON_MODE" ||
				xrandr --output "$monitor" --scale-from "$BEST_COMMON_MODE"
			else
				echo "Setting scale $MONITOR_RESULUTION for $monitor"
				xrandr --output "$monitor" --scale-from "$MONITOR_RESULUTION"
			fi
			[[ "$monitor" == "$REFERENCE_MONITOR" ]] ||
				xrandr --output "$monitor" --same-as "$REFERENCE_MONITOR" 
		done
		;;
	auto|auto-rtl|auto-ltr)
		DIRECTION=left
		[[ "$1" == "auto-rtl" ]] && DIRECTION=right
		xrandr --output "$REFERENCE_MONITOR" --primary
		xrandr | awk '/^[a-zA-Z0-9-]+ connected/ { print $1 }' | xargs -I MONITOR xrandr --output "MONITOR" --scale 1x1
		LAST_MONITOR="$REFERENCE_MONITOR"
		xrandr --output "$REFERENCE_MONITOR" --auto
		xrandr | awk '/^[a-zA-Z0-9-]+ connected/ { print $1 }' | while read monitor; do
			echo "$monitor"
			if ! [[ "$monitor" == "$REFERENCE_MONITOR" ]] ; then
				xrandr --output "$monitor" "--$DIRECTION-of" "$LAST_MONITOR" --auto
				LAST_MONITOR="$monitor"
			fi
		done
		;;
	*) echo "Unknown option!"; exit 2;;
esac
