#!/bin/bash
#
# This is an sdm burn plugin for: extractfs
#

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

function logtoboth() {
    echo "$1"
}

# $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="|bootfs|rootfs|burndev|burnfilefile|imgtype|" #"|list|of|valid|args|"
rqdargs="|imgtype|"                   # |list|of|required|args|or|nullstring|
assetdir="$SDMPT/etc/sdm/assets/$pfx"

if [[ "$phase" == "burn-complete" ]]
then
    logtoboth "* Plugin $pfx: Start Phase $phase"
    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
    [ -d $bootfs ] || logtobothex "? Plugin $pfx: bootfs target '$bootfs' must be a directory"
    [ -d $rootfs ] || logtobothex "? Plugin $pfx: rootfs target '$rootfs' must be a directory"
    dimg=$burndev
    [ "$dimg" == "" ] && dimg="$burnfilefile"
    declare -x SDMPT=$(makemtpt)
    domount "$dimg" $imgtype
    if [ "$bootfs" != "" ]
    then
	logtoboth "> Plugin $pfx: Copy bootfs from $SDMPT/boot/firmware to $bootfs"
	rsync -a --info=progress2 $SDMPT/boot/firmware $bootfs
    fi
    if [ "$rootfs" != "" ]
    then
	logtoboth "> Plugin $pfx: Copy rootfs from $SDMPT/boot to $rootfs"
	# Need to use -H b/c /usr/lib/aarch64-linux-gnu/ has 50+ hard-linked files
	rsync -aH --info=progress2 --exclude boot/firmware/* $SDMPT/ $rootfs
    fi
    docleanup
    exit
fi
