#!/usr/bin/perl
# 
# ***** BEGIN LICENSE BLOCK *****
# Zimbra Collaboration Suite Server
# Copyright (C) 2007, 2008, 2009, 2010, 2013, 2014, 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 *****
# 

use strict;
use Getopt::Std;
use File::Basename;

my $progname = basename($0);
# Need to be root to run "postfix status"
if ($> != 0) {
  print "$0 must be run as root.\n";
  exit 1;
}

# Exit if software-only node.
exit(1) unless (-f "/opt/zimbra/conf/localconfig.xml");

my %options = ();
unless ( getopts( 'dhv', \%options ) ) { usage(); }
usage() if ($options{h});
my $debug = $options{d} ? 1 : 0;
my $verbose = $options{v} ? 1 : 0;
$verbose = 1 if $debug;


my $postfix="/opt/zimbra/common/sbin/postfix";

exit (mtaIsRunning() ? 0 : 1);

sub mtaIsRunning {
  print "MTA process is " if $verbose;
  system("$postfix status 2> /dev/null");
  if ($? == 0) {
    print "running.\n" if $verbose;
    return 1;
  } else {
    print "not running.\n" if $verbose;
  }
  return undef;
}

sub getLocalConfig {
  my $key = shift;
  if (defined ($ENV{zmsetvars})) {
    return $ENV{$key};
  }
  open CONF, "/opt/zimbra/bin/zmlocalconfig -x -s -q -m shell |" or die "Can't open local config: $!";
  my @conf = <CONF>;
  close CONF;

  chomp @conf;

  foreach (@conf) {
    my ($key, $val) = split '=', $_, 2;
    $val =~ s/;$//;
    $val =~ s/'$//;
    $val =~ s/^'//;
    $ENV{$key} = $val;
  }
  $ENV{zmsetvars} = 'true';
  return $ENV{$key};
}

sub usage {
  print "$progname [-h] [-v] [-d]\n";
  print "\t-h\tUsage\n";
  print "\t-v\tverbose output\n";  
  print "\t-d\tdebug output\n";
  exit;
}

