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

BASE=/opt/zimbra
APACHECTL=$BASE/common/bin/apachectl
CONF=$BASE/conf/httpd.conf
PIDFILE=$BASE/log/httpd.pid

case "$1" in
	start)
		if [ -f $APACHECTL ]; then
      echo -n "Starting apache..."
			$APACHECTL -k $1 -f $CONF
      status=$?
      if [ $status = 0 ]; then
        echo "done."
      else
        echo "failed."
      fi
			exit $status
		fi
		exit 0
	;;
  reload|graceful)
		if [ -f $APACHECTL ]; then
      echo -n "Reloading apache..."
			$APACHECTL -k graceful -f $CONF
      status=$?
      if [ $status = 0 ]; then
        echo "done."
      else
        echo "failed."
      fi
			exit $status
		fi
		exit 0
	;;
  restart)
    $0 stop
    sleep 1
    $0 start
  ;;
	stop)
		if [ -f $PIDFILE ]; then
			if [ -f $APACHECTL ]; then
        echo -n "Stopping apache..."
				$APACHECTL -k $1 -f $CONF
        status=$?
        if [ $status = 0 ]; then
          echo "done."
        else
          echo "failed."
        fi
			  exit $status
			fi
		fi
		exit 0
	;;
	status)
    if [ -f $PIDFILE ]; then
		  pid=$(cat $PIDFILE)
      if [ x"$pid" = "x" ]; then
        echo "apache is not running."
        exit 1
      fi
    else
      echo "apache is not running."
      exit 1
    fi
    if ps --no-headers -p $pid -o cmd 2>/dev/null |grep httpd >/dev/null 2>&1; then
      echo "apache is running."
      exit 0
    else 
      echo "apache is not running."
		  exit 1
    fi
	;;
	*)
		echo "$0 start|stop|restart|reload|graceful|status"
		exit 1
	;;
esac
