#!/bin/dash
# jamesbond 2016
# idea from here: http://stackoverflow.com/questions/10500521/linux-retrieve-monitor-names

get_monitor_names() {
xrandr --verbose | 
awk '
# collect display names and its edid
/connected/ && !/disconnect/ { mon=$0; sub(/[ \t]+connected.*/,"",mon); monitor[mon]=mon; }	
/EDID:/ {
	str = ""
	getline
	while (!match($0,/:/)) {
		str = str $1
		getline
	}
	edid[mon]=str
}
END {
	for (mon in monitor) {
		print mon ": " get_monitor_name(edid[mon])
	}
}
function get_monitor_name(s,  s1,i) {
	for (i=0;i<3;i++) {
		s1=substr(s,(72+i*18)*2+1,18*2)	
		if (match(s1,/^000000fc00|^000000fe00/)) {
			s1=substr(s1,11) # skip 5-chars in hex digits (start at 1)
			return hex2str(s1)
		}
	}
	return "Unknown"
}
function hex2str(s, i,v,ret) {
	for (i=0; i<13*2; i+=2) {
		v = substr(s,i+1,2)
		ret = ret sprintf("%c", hex2byte(v))
	}
	return ret
}
function hex2byte(s, v,ret) {
	v=substr(s,1,1)
	ret = (index("0123456789abcdef",v)-1)*16
	v=substr(s,2,1)
	ret = ret + index("0123456789abcdef",v)-1
	if (ret < 32) return 32
	return ret
}

' | 
while read -r mon name; do
	echo $mon $name
done
}

get_monitor_names
