#!/bin/bash
#
# This is an sdm plugin for: piapps
#
# 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
args="$2"
loadparams
vldargs="|user|"
rqdargs=""                   # |list|of|required|args|or|nullstring|
assetdir="$SDMPT/etc/sdm/assets/$pfx"

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
    #mkdir -p $assetdir
    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"
elif [ "$phase" == "post-install" ]
then
    #
    # 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"
    [ "$user" != "" ] && buser=$user
    [ "$buser" == "" ] && buser=$myuser
    if [[ "$buser" != "" ]]
    then
	logtoboth "> Plugin $pfx: Install pi-apps from https://github.com/Botspot/pi-apps using user $buser"
	hostname $thishost   #pi-apps installer looks up hostname for some reason?
	su $buser -c 'wget -qO- https://raw.githubusercontent.com/Botspot/pi-apps/master/install | bash'
	hostname sdm
    else
	logtobothex "? Plugin $pfx: User not specified with 'user' argument nor established with the 'user' plugin"
    fi
    plugin_addnote ""
    plugin_addnote "*** piapps notes ***"
    plugin_addnote ""
    plugin_addnote " * Desktop asks what you want to do with Pi-Apps executable script"
    plugin_addnote "   * File Manager: Edit|Preferences|Don't ask options on launch executable file"
    plugin_addnote ""
    plugin_addnote "See https://github.com/Botspot/pi-apps for questions/issues/etc"

    #logfreespace "at end of $pfx Custom Phase post-install"
    logtoboth "* Plugin $pfx: Complete Phase post-install"
fi
