#!/bin/bash
### BEGIN INIT INFO
# Provides:          framebuffer-start
# Required-Start:    mountkernfs
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Initializes console output over HDMI
### END INIT INFO

# . /lib/lsb/init-functions

parse_mode() {
    M=$1
    
    # We want to parse mode names like the following:
    # 
    #   480i60hz
    #   576p_rpt
    #   1080p60hz
    #   2160p60hz420
    #   1024x768p60hz
    #
    # From this we want to get the X and Y resolutiions.  We don't 
    # care here about the refresh rate, interlace mode or other 
    # features.
    # 
    # In the case of the TV modes the mode name doesn't explicity 
    # tell us the X dimension, but we can use arithmetic to work 
    # that out if we assume the aspect ratio.
    # 
    # This is obviously fragile if new mode names with different 
    # formats are added.
    
    # Mode name is in $M.
    
    # Allow for uppercase X:
    M=`echo $M | tr X x`
    
    # We'll parse in two steps.  First, we'll get the initial numbers 
    # and possible x, i.e. everything before the 'i' or 'p'.  That will 
    # either be XxY for the VESA modes or just Y for the TV modes.
    
    XY=`echo $M | sed 's/^\([0-9x]*\).*$/\1/'`
    
    # Check for VESA XxY
    # (Note that we need egrep below because regular grep doesn't 
    # support the + syntax.)
    if echo $XY | egrep -q '^[0-9]+x[0-9]+$'
    then
      X=`echo $XY | sed 's/^\([0-9]*\)x\([0-9]*\)$/\1/'`
      Y=`echo $XY | sed 's/^\([0-9]*\)x\([0-9]*\)$/\2/'`
    
    # Check for TV Y-only
    elif echo $XY | egrep -q '^[0-9]+$'
    then
      Y=$XY
      # Assume 16:9 aspect ratio
      X=$(($Y * 16 / 9))
    
    else
      echo "Don't understand mode '$M'" 1>&2
      exit 1
    fi
}


setup_display() {
    for x in $(cat /proc/cmdline); do
        case ${x} in
            m_bpp=*)    export bpp=${x#*=} ;;
            hdmimode=*) export mode=${x#*=} ;;
        esac
    done
    parse_mode "${mode}"

    echo $mode > /sys/class/display/mode
    M="0 0 $(($X - 1)) $(($Y - 1))"
    Y_VIRT=$(($Y * 2))
    fbset -fb /dev/fb0 -g $X $Y $X $Y_VIRT $bpp
    fbset -fb /dev/fb1 -g 32 32 32 32 32
    echo $mode > /sys/class/display/mode
    echo 0 > /sys/class/graphics/fb0/free_scale
    echo 1 > /sys/class/graphics/fb0/freescale_mode
    echo $M > /sys/class/graphics/fb0/free_scale_axis
    echo $M > /sys/class/graphics/fb0/window_axis
    echo 0 > /sys/class/graphics/fb1/free_scale

    echo 0 > /sys/class/graphics/fb0/blank
    echo 0 > /sys/class/graphics/fb1/blank

    echo "0" > /sys/devices/platform/mesonfb/graphics/fb1/blank
}


case "$1" in
    start)
    log_action_begin_msg "Enable console output over HDMI"
    setup_display
    log_action_end_msg 0
    ;;

    *)
    echo "Usage: /etc/init.d/$0 start"
    exit 1

esac

