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

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

# $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
allargs="$2"
loadparams
vldargs="|script|user|sudoswitches|args|output|error|"
rqdargs="|script|"
assetdir="$SDMPT/etc/sdm/assets/runatboot"

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 "$allargs" "$vldargs" "$rqdargs" || exit
    plugin_printkeys
    mkdir -p $assetdir
    if [ -f $script ]
    then
	sbn=$(basename $script)
	cp -a $script $assetdir/${sbn}
	sfn="$SDMPT/etc/sdm/0piboot/060-runatboot.sh"
	if [ ! -f $sfn ]
	then
	    cat > $sfn <<EOF
#!/bin/bash
logger "sdm FirstBoot: Run runatboot scripts"
EOF
	fi
	[ "$output" == "" ] && output=">/dev/null" || output=">$output"
	[ "$error" == "" ] && error="2>&1" || error="2>$error"
	if [ "$user" != "" ]
	then
	    xdo="sudo -u $user $sudoswitches "
	    xstr=" as user '$user'"
	else
	    xdo=""
	    xstr=""
	fi
	logtoboth "> Plugin $pfx: Set script '$sbn' in '$sfn' to run at first system boot${xstr}"
	cat >> $sfn <<EOF
if [ "$xdo" != "" ]
then
    if ! getent passwd $user > /dev/null
    then
        logger "sdm FirstBoot: User '$user' for runatboot plugin script '$sbn' does not exist"
        exit
    fi
    logger "sdm FirstBoot: Copy runatboot script /etc/sdm/assets/runatboot/${sbn} to /tmp to run${xstr}"
    cp /etc/sdm/assets/runatboot/${sbn} /tmp
    chown $user /tmp/${sbn}
    runfile="/tmp/${sbn}"
else
    runfile="/etc/sdm/assets/runatboot/${sbn}"
fi
logger "sdm FirstBoot: Run runatboot script '${sbn}'${xstr}: \$runfile $args $output $error"
chmod 755 \$runfile
${xdo}\$runfile $args $output $error
EOF
    else
	logtobothex "? Plugin $pfx: Script file '$script' not found"
    fi
    logtoboth "* Plugin $pfx: Complete Phase 0"

elif [ "$phase" == "1" ]
then
    #
    # Phase 1 (in nspawn)
    #
    logtoboth "* Plugin $pfx: Start Phase 1"
    plugin_getargs $pfx "$allargs" "$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 "$allargs" "$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
