#!/bin/bash
#
# This is an sdm plugin for: chrony
#
# 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="|conf|conf2|conf3|sources|sources2|sources3|nodistsources|"
rqdargs=""
assetdir="$SDMPT/etc/sdm/assets/chrony"

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" || exit
    #
    # Print the keys found (example usage). plugin_getargs returns the list of found keys in $foundkeys
    #
    plugin_printkeys
    #
    # Copy files into the IMG
    #
    for id in conf conf2 conf3 sources sources2 sources3
    do
	idf="${!id}"
	if [ "$idf" != "" ]
	then
	    if [ -f $idf ]
	    then
		did="${id%%[0-9]}"    #Strip digits for assets subdir name
		logtoboth "> Plugin $pfx: Copy '$id' config file '$idf' to $assetdir/$did"
		mkdir -p $assetdir/$did
		cp -a $idf $assetdir/$did
	    else
		logtobothex "? Plugin $pfx: '$id' config file '$idf' not found"
	    fi
	fi
    done
    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"
    logtoboth "> Plugin $pfx: Install chrony"
    installpkgsif chrony
    logtoboth "* Plugin $pfx: Complete Phase 1"
else
    #
    # Plugin Post-install edits
    #
    logtoboth "* Plugin $pfx: Start Phase post-install"
    plugin_getargs $pfx "$args" "$vldargs"
    for id in conf sources
    do
	if compgen -G "$assetdir/$id/*.$id" > /dev/null
	then
	    logtoboth "> Prefix $pfx: Copy $id config files to /etc/chrony/$id.d"
	    cp -a $assetdir/$id/*.$id /etc/chrony/$id.d
	fi
    done

    if [ -v nodistsources ]
    then
	if compgen -G "$assetdir/sources/*.sources" > /dev/null
	then
	    logtoboth "> Plugin $pfx: Disable time servers defined in /etc/chrony.conf"
	    cp -a /etc/chrony/chrony.conf /etc/chrony/chrony.conf.sdm
	    sed -i "s/^pool/#pool/" /etc/chrony/chrony.conf
	fi
    fi

    logtoboth "* Plugin $pfx: Complete Phase post-install"
fi
