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

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

function geninstance() {
    #
    # make a unique instance name for assets
    #
    instance="$from-$to"
    instance=${instance//\/}  # Remove slashes
}

function runrsync() {
    #
    # $1: from
    # $2: to
    # $3: rsyncopts
    # $4: stdout
    # $5: stderr
    local from=$1 to=$2 rsyncopts=$3 stdout="$4" stderr="$5"
    [ "$rsyncopts" == "" ] && aa="-a" || aa=""
    [ "$stdout" == "" ] && stdout="/dev/null"
    [ "$stderr" == "" ] && stderr="/dev/null"
    logtoboth "> Plugin $pfx: rsync $aa $rsyncopts $from $to"
    # Log the command in stdout so they can be differentiated if needed
    echo "rsync $aa $rsyncopts $from $to" >>$stdout
    rsync $aa $rsyncopts $from $to >>$stdout 2>>$stderr
    echo "" >>$stdout
}

# $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="|from|to|rsyncopts|stdout|stderr|"
rqdargs="|from|to|"                   # |list|of|required|args|or|nullstring|
assetdir="$SDMPT/etc/sdm/assets/$pfx"
instance=""

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
    plugin_printkeys
    mkdir -p $assetdir
    # nodirect will never be defined so will always use direct copy
    if [ ! -v nodirect ]
    then
	# Direct copy in Phase 0 using rsync
	runrsync $from $SDMPT/$to "$rsyncopts" "$stdout" "$stderr"
    else
	# Stage it into $assetdir
	geninstance
	runrsync $from $assetdir/$instance "$rsyncopts" "$stdout" "$stderr"
    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"
    if [ -v nodirect ]
    then
	geninstance
	runrsync $assetdir/$instance/ $to "$rsyncopts" "$stdout" "$stderr"
    fi
    #logfreespace "at end of $pfx Custom Phase post-install"
    logtoboth "* Plugin $pfx: Complete Phase post-install"
fi
