#!/bin/sh
#
#
# NOTICE OF LICENSE
#
# This source file is subject to the Open Software License (OSL 3.0)
# that is available through the world-wide-web at this URL:
# http://opensource.org/licenses/osl-3.0.php
#
#
# The appserver control script designed to allow an easy command line interface
# to controlling the PHP-FPM daemon. Written by Tim Wagner, 2013/07/24
#
# The exit codes returned are:
#   XXX this doc is no longer correct now that the interesting
#   XXX functions are handled by appserver
#	0 - operation completed successfully
#	1 -
#	2 - usage error
#	3 - php-fpm could not be started
#	4 - php-fpm could not be stopped
#	5 - php-fpm could not be started during a restart
#	6 - php-fpm could not be restarted during a restart
#	7 - php-fpm could not be restarted during a graceful restart
#	8 - configuration syntax error
#
# When multiple arguments are given, only the error from the _last_
# one is reported.  Run "appserver-php5-fpmctl help" for usage info
#
ARGV="$@"
#
# |||||||||||||||||||| START CONFIGURATION SECTION  ||||||||||||||||||||
# --------------------                              --------------------
#
# pick up any necessary environment variables
if test -f /usr/sbin/envvars; then
  . /usr/sbin/envvars
fi
# --------------------                              --------------------
# ||||||||||||||||||||   END CONFIGURATION SECTION  ||||||||||||||||||||

LAUNCHCTL="/bin/launchctl"
JOB_LABEL="io.appserver.appserver-php5-fpm"
LAUNCHD_JOB="/opt/appserver/sbin/plist/$JOB_LABEL.plist"

run_launchctl() {
    if [ $UID != 0 ]; then
        echo This operation requires root.
        exit 1
    fi
    $LAUNCHCTL $@
}

display_help() {
    echo "usage $0 [start|restart|graceful|stop|status|graceful-stop]
    (see php-fpm documentation for more info)"
}

ERROR=0
if [ "x$ARGV" = "x" ] ; then
    ARGV="-h"
fi

case $ARGV in
start)
    run_launchctl load -w $LAUNCHD_JOB
    ERROR=$?
    ;;
stop|graceful-stop)
    run_launchctl unload -w $LAUNCHD_JOB
    ERROR=$?
    ;;
status)
    run_launchctl list $JOB_LABEL
    ERROR=$?
    ;;
restart|graceful)
    run_launchctl unload -w $LAUNCHD_JOB 2> /dev/null
    run_launchctl load -w $LAUNCHD_JOB
    ERROR=$?
    ;;
help|-h|--help|*)
    display_help
    ERROR=1
    ;;
esac

exit $ERROR