#!/bin/bash
#
# Guralp Configuration System
#   Copyright (c) 2008-2009 Guralp Systems Ltd. All rights reserved.
#
#   Postoffice MTA

# Quick exit for navbar query
if [ "X$1" == "X--navbar" ]
then
	echo "networktop	Networking"
	echo "mta	Mail"
	exit 0
fi

# Load support functions
script_dir=$(dirname $0)
. $script_dir/functions.sh
. $script_dir/svc_funcs.sh

CFFILE="/etc/mail/postoffice.cf.local"
ALIASFILE="/etc/mail/aliases.local"
ENABFILE=$CONFDIR/mta

do_read() {
	local hostname
	local postalias

	gcs_var d_enablemta	"True"
	gcs_var d_smarthost	""
	gcs_var d_mailhostname	""
	gcs_var d_postalias	""

	# Enable flag
	if [ -r $ENABFILE ]
	then
	    source $ENABFILE
	    [ -n "$ENABLE" ] && gcs_var o_enablemta "$ENABLE"
	fi

	# Main cf file parameters
	if [ -r $CFFILE ]
	then
	    hostname=$(gcs_get_varf relay-host $CFFILE)
	    [ -n "$hostname" ] && gcs_var o_smarthost "$hostname"

	    hostname=$(gcs_get_varf self $CFFILE)
	    [ -n "$hostname" ] && gcs_var o_mailhostname "$hostname"
	fi

	# Root alias
	if [ -r $ALIASFILE ]
	then
	    postalias=$(gcs_get_cvarf root $ALIASFILE)
	    [ -n "$postalias" ] && gcs_var o_postalias "$postalias"
	fi
}

do_check() {
	gcs_read_vars

	# Simple checking is now down by the config engine
}

do_write() {
	local err

	do_check
	if (( gcs_errors > 0 ))
	then
	    return
	fi

	gcs_set_varf ENABLE $ENABFILE $new_enablemta
	gcs_set_varf relay-host $CFFILE $new_smarthost
	gcs_set_varf self $CFFILE $new_mailhostname
	gcs_set_cvarf root $ALIASFILE $new_postalias
	newaliases 2> /dev/null
	if [ $? -ne 0 ]
	then
		gcs_err fatal "Failed to write alias database:"
		newaliases
	fi

	gcs_svc_reload "mta"
	return 0
}


case "X$1" in
X--check)	do_check	;;
X--write)	do_write	;;
X--read)	do_read	;;
*)		exit 1	;;
esac

gcs_cleanup
exit 0
