#!/bin/sh

if [ -z "$1" -o "$1" = "-h" ]; then
	echo "usage: $0 [-d display] [-o output] [-r refrash] [-m mode] [-s scale_x scale_y]"
	exit
fi

display=
output=
rate=
mode=

while [ "$1" ]; do
	case $1 in
		-d)
			shift
			display=$1
			;;
		-o)
			shift
			output=$1
			;;
		-r)
			shift
			rate=$1
			;;
		-m)
			shift
			mode=$1
			;;
		-s)
			shift
			scale_x=$1
			scale_y=$2
			shift
			;;
	esac
	shift
done

if [ -z "$display$DISPLAY" ]; then
	display=:0
fi

display=${display:+--display $display}

if [ -z "$output" ]; then
	output="$( (xrandr $display | grep " connected " | grep "^HDMI" || xrandr $display | grep " connected ") | head -n1 | cut -d" " -f1)"
	if [ ! "$output" ]; then
		exit 1
	fi
fi

if [ -z "$mode" ]; then
	mode="$(xrandr $display | grep -A 100 "^$output " | grep "*" | head -n1 | sed "s/ *\([0-9x]*\).*/\\1/")" #"
	if [ ! "$mode" ]; then
		exit 1
	fi
fi

if ! xrandr $display --output $output --mode $mode ${rate:+--rate $rate} &>/dev/null && [ "$rate" ]; then
	if xrandr $display | grep -q "${mode}_${rate} "; then
		:
	elif [ -e /etc/X11/edid.bin ]; then
		cat /etc/X11/edid.bin | parse-edid 2>/dev/null | grep Modeline | while read _ _ _ v1 v2 v3 v4 v5 v6 v7; do
			if [ "$mode" = "${v2}x${v6}$(test "${v7##*interlace*}" || echo i)" ]; then
				xrandr $display --newmode ${mode}_$rate $v1 $v2 $v3 $v4 $v5 $v6 $v7
				xrandr $display --addmode $output ${mode}_$rate
				xrandr $display | grep ${mode}_$rate | grep -q $rate.00 && break
				xrandr $display --delmode $output ${mode}_$rate
				xrandr $display --rmmode ${mode}_$rate
			fi
		done
	else
		modeline=$(cvt $(test ${mode%%*i} || echo -i) ${mode%x*} ${mode#*x} $rate | grep Modeline | cut -d" " -f 4- | sed 's/"//g')
		xrandr $display --newmode ${mode}_$rate $modeline
		xrandr $display --addmode $output ${mode}_$rate
	fi
	xrandr $display --output $output --mode ${mode}_$rate
fi

if [ "$scale_x" -a "$scale_y" ]; then
	x=$scale_x
	y=$scale_y
	w=${mode%x*}
	h=${mode#*x}
	if [ -x /usr/bin/nvidia-settings ]; then
		if [ $x -ge 0 ]; then px=$x; nx=0; else px=0; nx=$((-($x))); fi
		if [ $y -ge 0 ]; then py=$y; ny=0; else py=0; ny=$((-($y))); fi
		nvidia-settings $display -a CurrentMetaMode="$output: $mode+$nx+$ny { ViewPortIn=$(($w-$nx-$nx))x$(($h-$ny-$ny)), ViewPortOut=$(($w-$px-$px))x$(($h-$py-$py))+$px+$py }"
	else
		xrandr $display --output $output --mode $mode --transform $(echo "scale=2;($w+$x+$x)/$w"|bc),0,$((-($x))),0,$(echo "scale=2;($h+$y+$y)/$h"|bc),$((-($y))),0,0,1
	fi
fi
