#!/bin/bash
#
# This is an sdm plugin for: bootconfig
#
# The plugin is called three times: for Phase 0, Phase 1, and post-install.
#

function loadparams() {
    source $SDMPT/etc/sdm/sdm-readparams
}

function writecfg() {
    local msg="$1"
    [ ${#msg} -gt 96 ] && logtobothex "? Plugin $pfx: config.txt line too long (${#msg}>96): $msg"
    printf "$1" >>$cfgdir/config.txt
}

function updateconfigtxt() {
    local c="$1" value="$2" pfx="$3" inline="$4" newsection="$2" dnm drest dsep sname sval
    if [ "$c" == "section" ]
    then
	logtoboth "> ${pfx}Append section '$value' to $cfgdir/config.txt"
	[ "$newsection" == "${newsection#[}" ] && newsection="[$newsection]"
	writecfg "\n${newsection}\n"
    else
	# assume not dtoverlay/dtparam
	sname="$c"
	sval="$value"
	dsep="="
	if [[ "dtoverlay|dtparam" =~ "$c" ]]
	then
	    # dtoverlay/dtparam. Pick apart further
	    # We search config.txt for 'dtxxx=dtname' instead of just 'dtxxx'
	    if [ "$value" != "" ]
	    then
		#dsep="="  # default set above
		dnm=${value%%=*}
		drest=${value#*=}
		if [[ "$dnm" == "$value" ]] || [[ "$drest" =~ "," ]]
		then
		    # Not dtxxx=dnm=xx see if dtxxx=dnm,something
		    # or it could be dtxxx=dnm,foobar=12 (comma in $drest)
		    if [[ "$drest" =~ "," ]]
		    then
			dsep=","
			dnm=${value%%,*}
			drest=${value#*,}
		    else
			dsep=""
			dnm=${value%%,*}
			drest=""
		    fi
		fi
	    else
		logtoboth "? ${pfx}Error detected in updateconfigtxt. Please report error along with command line on GitHub"
		logtobothex "  Details: c:|$c| value:|$value|"
	    fi
	    sname="${c}=${dnm}"
	    sval="${drest}"
	fi
	if [ "$inline" != "" ]
	then
	    if grep -q "^#$sname.*" $cfgdir/config.txt
	    then
		# there but commented out
		logtoboth "> ${pfx}Adding '${sname}${dsep}${sval}' below already commented line in $cfgdir/config.txt"
		sed -i "/^#$sname=.*/a $sname${dsep}$sval" $cfgdir/config.txt
	    else
		if grep -q "^$sname.*" $cfgdir/config.txt
		then
		    # There and uncommented
		    if grep -q "$^sname${dsep}" $cfgdir/config.txt
		        then
		        logtoboth "> Add '${sname}${dsep}${sval}' below newly commented line it replaces ${sname}${dsep}"
		        sed -i "s/^${sname}${dsep}/#sdm: $sname${dsep}/" $cfgdir/config.txt
		        sed -i "/^#sdm: $sname${dsep}.*/ a $sname${dsep}$sval" $cfgdir/config.txt
		    elif [[ $dsep == "," ]]
		    then
		        logtoboth "> Add '${sname}${dsep}${sval}' below newly commented line it replaces ${sname}"
		        sed -i "s/^${sname}/#sdm: $sname/" $cfgdir/config.txt
		        sed -i "/^#sdm: $sname.*/ a $sname${dsep}$sval" $cfgdir/config.txt
		    fi
		else
		    # Not in config.txt
		    logtoboth "> ${pfx}Append '${sname}${dsep}${sval}' to $cfgdir/config.txt"
		    writecfg "${sname}${dsep}${sval}\n"
		fi
	    fi
	else
	    #
	    # Not inline, so always append
	    #
	    logtoboth "> ${pfx}Append '${sname}${dsep}${sval}' to $cfgdir/config.txt"
	    writecfg "${sname}${dsep}${sval}\n"
	fi
    fi

}

# $1 is the phase: "0", "1", or "post-install"
# $2 is the argument list: arg1=val1|arg2=val2|arg3=val3| ...
#
# Main code for the Plugin
#
phase=$1
pfx="$(basename $0)"     #For messages
args="$2"
loadparams
vldargs=""
rqdargs=""
assetdir="$SDMPT/etc/sdm/assets/bootconfig"
[ -d $SDMPT/boot/firmware ] && cfgdir="$SDMPT/boot/firmware" || cfgdir="$SDMPT/boot"

if [ "$phase" == "0" ]
then
    #
    # In Phase 0 all references to directories in the image must be preceded by $SDMPT
    #
    logtoboth "* Plugin $pfx: Start Phase 0"
    plugin_getargs $pfx "$args" "$vldargs" "$rqdargs" || exit
    #
    # Print the keys found (example usage). plugin_getargs returns the list of found keys in $foundkeys
    #
    plugin_printkeys
    if [ "$foundkeys" != "" ]
    then
	logtoboth "> Plugin $pfx: Processing keys..."

	# special processing for certain keys
	[ -v inline ] && inline="1"
	[ -v hdmi_ignore_edid -a "$hdmi_ignore_edid" == "" ] && hdmi_ignore_edid="0xa5000080"

	IFS="|" read -a fargs <<< "$foundkeys"
	for c in "${fargs[@]}"
	do
	    value="${!c}"
	    case "$c" in
		comment)
		    logtoboth "> Plugin $pfx: Add comment to $cfgdir/config.txt: $value"
		    #[ "$value" != "${value#\\n}" ] && value="\n#${value#\\n}" || value="#${value}"
		    writecfg "$value\n"
		    ;;
		#inline)
		    #inline="1"  # Already set above of course
		    #;;
		reset)
		    if [ "$reset" != "" ]
		    then
			if [ -f $reset ]
			then
			    logtoboth "% Plugin $pfx: Reset $cfgdir/config.txt with '$reset'"
			    [ ! -f $cfgdir/config.txt.sdm ] && mv $cfgdir/config.txt $cfgdir/config.txt.sdm
			    rm -f $cfgdir/config.txt
			    cp -a $reset $cfgdir/config.txt
			    setfileownmode $cfgdir/config.txt 644  #Doesn't matter on FAT, but wth
			else
			    logtobothex "? Plugin $pfx: $cfgdir/config.txt reset file '$reset' not found"
			fi
		    else
			logtoboth "% Plugin $pfx: Reset $cfgdir/config.txt to null file"
			[ ! -f $cfgdir/config.txt.sdm ] && mv $cfgdir/config.txt $cfgdir/config.txt.sdm
			rm -f $cfgdir/config.txt
			touch $cfgdir/config.txt
		    fi
		    ;;
		*)
		    [ "$c" != "inline" ] && updateconfigtxt "$c" "$value" "Plugin $pfx: " "$inline"
		;;
	    esac
	done
    fi
    logtoboth "* Plugin $pfx: Complete Phase 0"

elif [ "$phase" == "1" ]
then
    #
    # Phase 1 (in nspawn)
    #
    logtoboth "* Plugin $pfx: Start Phase 1"
    plugin_getargs $pfx "$args" "$vldargs" "$rqdargs"
    #logfreespace "at start of Plugin $pfx Phase 1"
    #
    #logfreespace "at end of $pfx Phase 1"
    logtoboth "* Plugin $pfx: Complete Phase 1"
else
    #
    # Plugin Post-install edits
    #
    logtoboth "* Plugin $pfx: Start Phase post-install"
    plugin_getargs $pfx "$args" "$vldargs" "$rqdargs"
    #logfreespace "at start of Plugin $pfx Phase post-install"
    #
    #logfreespace "at end of $pfx Custom Phase post-install"
    logtoboth "* Plugin $pfx: Complete Phase post-install"
fi
