#!/bin/sh
# Steven Bromley

# HFP-123: HDMI Hotplug support

set -u

SYSFS_FB0=/sys/class/graphics/fb0

if [ -n "${DEBUG:-}" ]; then
   DEBUG=true
   set -x
else
   DEBUG=false
   exec 2>/dev/null
fi

expand_modestr() {
  # Reformat each mode string and delimit with tabs, as follows:
  #   Input:	D:1920x1080p-60
  #   Output:	1920	1080	60	D:1920x1080p-60	D
  # Width and height are placed first for easy numeric sorting.
  # ModeType (DVSU) is placed last for easy filtering by grep in select_mode
  # Interlaced modes are ignored as we don't support them anyway.
  sed -ne 's/^\([A-Z]\):\([0-9]\+\)x\([0-9]\+\)p-\([0-9]\+\)$/\2\t\3\t\4\t\0\t\1/p'
}

select_mode() {
  # Select the most suitable mode-string from a list of modes (read from stdin)
  # We want the highest resolution mode <= 1920x1200 with refresh 50-100Hz
  local modes=$(expand_modestr | sort -nr)
  
  # Examine "detailed" modes first (D=Detailed, V=VESA, S=Standard, U=Undefined(?))
  for re in 'D$' '[VS]$' '[^DVS]$'; do
    echo "$modes" | grep "$re"
    
  done | while read width height refresh modestr modetype; do
    if [ $width -le 1920 -a $height -le 1200 -a $refresh -ge 50 -a $refresh -le 100 ]; then
      echo "$modestr"
      break
    fi
  done
}

wait_modelist_change() {
  while true; do
    local prv_mode=$(cat $SYSFS_FB0/mode) 
    local prv_modelist=$(cat $SYSFS_FB0/modes)

    # Ideally we'd wait here for an HDMI-plugin event.
    # sysfs and procfs dont support inotify, so the best way is to use udevadm to listen for kernel events.
    # In that case we'd have to read line-by-line, which requires "stdbuf" in the platform - it currently isn't included.
    #	eg: stdbuf -oL udevadm monitor | grep '/devices/mxc_hdmi'
    # For now, just poll for changes in the modelist.  
    while true; do
      local new_modelist=$(cat $SYSFS_FB0/modes)
      
      if [ "$prv_modelist" != "$new_modelist" ]; then
	break
      else
	sleep 1
      fi
    done

    local new_mode=$(echo "$new_modelist" | select_mode)
    
    echo "New modelist detected (prv_mode=$prv_mode, new_mode=$new_mode):"
    echo "$new_modelist"

    if [ "$new_mode" != "$prv_mode" ]; then
      # Set the new mode
      echo "$new_mode" > $SYSFS_FB0/mode
      
      # Check whether the resolution (only) has changed
      if [ "$(echo "$new_mode" | expand_modestr | cut -f1-2)" \
	!= "$(echo "$prv_mode" | expand_modestr | cut -f1-2)" ]
      then
	echo "Resolution changed"
	break
      fi
    fi
  done >&2
}

wait_modelist_change
exit 0
