#!/bin/bash
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
# Copyright 2016 Igor Kozhukhov.
#

. /lib/svc/share/smf_include.sh

#if startup options contain multiple arguments separated by a blank,
#then they should be specified as below
#e.g., %> svccfg -s apache24 setprop httpd/startup_options=\("-f" "/etc/apache2/2.4/new.conf"\)
#
STARTUP_OPTIONS=

getprop() {
    PROPVAL=""
    svcprop -q -p "$1" ${SMF_FMRI}
    if [ $? -eq 0 ] ; then
        PROPVAL=`svcprop -p "$1" ${SMF_FMRI}`
        if [ "${PROPVAL}" = "\"\"" ] ; then
            PROPVAL=""
        fi
        return
    fi
    return
}

NAME=apache2
DAEMON=/usr/sbin/$NAME
APACHE_CONFDIR=/etc/apache2
if [ -z "$APACHE_ENVVARS" ] ; then
	APACHE_ENVVARS=$APACHE_CONFDIR/envvars
fi
export APACHE_CONFDIR APACHE_ENVVARS

ENV="env -i SMF=yes LANG=C PATH=/usr/sbin:/usr/bin:/sbin"
if [ "$APACHE_CONFDIR" != /etc/apache2 ] ; then
	ENV="$ENV APACHE_CONFDIR=$APACHE_CONFDIR"
fi
if [ "$APACHE_ENVVARS" != "$APACHE_CONFDIR/envvars" ] ; then
	ENV="$ENV APACHE_ENVVARS=$APACHE_ENVVARS"
fi

# Now, set defaults:
APACHE2CTL="$ENV /usr/sbin/apache2ctl"

apache_conftest() {
	[ -z "$CONFTEST_OUTFILE" ] || rm -f "$CONFTEST_OUTFILE"
	CONFTEST_OUTFILE=$(mktemp)
	if ! $APACHE2CTL configtest > "$CONFTEST_OUTFILE" 2>&1 ; then
		return 1
	else
		rm -f "$CONFTEST_OUTFILE"
		CONFTEST_OUTFILE=
		return 0
	fi
}

cmd=''
case "$1" in
start)
	if apache_conftest ; then
		cmd="start"
	else
		exit $SMF_EXIT_ERR_CONFIG
	fi
	;;
refresh)
	cmd="graceful"
	;;
stop)
	cmd="stop"
	;;
*)
	echo "Usage: $0 {start|stop|refresh}"
	exit $SMF_EXIT_ERR_CONFIG
	;;
esac

$APACHE2CTL ${cmd}

if [ $? -ne 0 ]; then
    echo "Server failed to start. Check the error log (defaults to /var/log/apache2/error.log) for more information, if any."
    exit $SMF_EXIT_ERR_FATAL
fi

exit $SMF_EXIT_OK
