#!/bin/bash
#
# This is an sdm plugin for: logwatch
#
# 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"
vldargs="|config|sendto|sendfrom|"
assetdir="$SDMPT/etc/sdm/assets/logwatch"
loadparams

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
    plugin_printkeys
    mkdir -p $assetdir
    if [ "$config" != "" ]
    then
	if [ -d $config ]
	then
	    logtoboth "> Plugin $pfx: Copy local logwatch config subtree to $assetdir/config"
	    mkdir -p $assetdir/config
	    rsync -a $config/ $assetdir/config

	fi
    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" || exit
    logtoboth "> Plugin $pfx: Install logwatch"
    installpkgsif logwatch
    if [ -d $assetdir/config ]
    then
	logtoboth "> Plugin $pfx: Copy local logwatch config files into /etc/logwatch"
	rsync -a $assetdir/config/ /etc/logwatch
	if [ -f /etc/logwatch/conf/logwatch.conf ]
	then
	    cp /etc/logwatch/conf/logwatch.conf /etc/logwatch/conf/logwatch.conf.sdm
	    if [ "$sendto" != "" ]
	    then
		sendto=$(stripquotes "$sendto")
		logtoboth "> Plugin $pfx: Set MailTo '$sendto' in logwatch.conf"
		sed -i "s/^MailTo = .*/MailTo = $sendto/" /etc/logwatch/conf/logwatch.conf
	    fi
	    if [ "$sendfrom" != "" ]
	    then
		sendfrom=$(stripquotes "$sendfrom")
		logtoboth "> Plugin $pfx: Set MailFrom '$sendfrom' in logwatch.conf"
		sed -i "s/^MailFrom = .*/MailFrom = $sendfrom/" /etc/logwatch/conf/logwatch.conf
	    fi
	fi
    fi
    logtoboth "* Plugin $pfx: Complete Phase 1"
else
    #
    # Plugin Post-install edits
    #
    logtoboth "* Plugin $pfx: Start Phase post-install"

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