#!/bin/bash
# 
# ***** BEGIN LICENSE BLOCK *****
# Zimbra Collaboration Suite Server
# Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2013, 2014, 2015, 2016 Synacor, Inc.
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software Foundation,
# version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this program.
# If not, see <https://www.gnu.org/licenses/>.
# ***** END LICENSE BLOCK *****
# 

progdir=`dirname $0`

source `dirname $0`/zmshutil || exit 1

if [ ! -x /opt/zimbra/common/sbin/postfix ]; then
  echo "Error: postfix not installed"
  exit 1
fi

zmsetvars

rewritemtaconfig() {
    /opt/zimbra/libexec/zmmtainit
}

rewriteconfig() {
    /opt/zimbra/libexec/configrewrite mta > /dev/null 2>&1
}

if [ "x$1" = "xstatus" -o "x$1" = "xstart" ]; then
  if [ ! -f /opt/zimbra/common/conf/main.cf ]; then
    touch /opt/zimbra/common/conf/main.cf
    /opt/zimbra/common/sbin/postconf -e mail_owner=${postfix_mail_owner} setgid_group=${postfix_setgid_group}
  fi
  sudo /opt/zimbra/libexec/zmmtastatus 2> /dev/null
	R=$?
	if [ "x$1" = "xstart" ]; then
		if [ "x$R" = "x0" ]; then
			exit 0
		fi
	else
		if [ x$R != "x0" ]; then
			exit 1
		else
			exit 0
		fi
	fi
fi

if [ "x$1" = "xstart" -o "x$1" = "xreload" -o "x$1" = "xrestart" ]; then
	rewritemtaconfig
	if [ "x$2" != "xnorewrite" ]; then
		rewriteconfig
	fi
fi

if [ -f /etc/aliases ]; then
  sudo /opt/zimbra/common/sbin/postalias /etc/aliases
fi

sudo /opt/zimbra/common/sbin/postfix "$@"

