#!/bin/bash
#
# pe-httpd     Startup script for the Puppet Labs (Apache) HTTP Server
#
# chkconfig: - 85 15
# description: The Apache HTTP Server is an efficient and extensible  \
#	       server implementing the current HTTP standards.
# processname: pe-httpd
# config: /etc/puppetlabs/httpd/conf/pe-httpd.conf
# config: /etc/sysconfig/pe-httpd
# pidfile: /var/run/pe-httpd/pe-httpd.pid
#
### BEGIN INIT INFO
# Provides: pe-httpd
# Required-Start: $local_fs $remote_fs $network $named
# Required-Stop: $local_fs $remote_fs $network
# Should-Start: distcache
# Short-Description: start and stop Apache HTTP Server
# Description: The Apache HTTP Server is an extensible server 
#  implementing the current HTTP standards.
### END INIT INFO

# Customized by Dell

# Source function library.
. /etc/rc.d/init.d/functions

if [ -f /etc/sysconfig/pe-httpd ]; then
        . /etc/sysconfig/pe-httpd
fi

if [ -f /etc/puppetlabs/installer/answers.install ]; then
    . /etc/puppetlabs/installer/answers.install
fi

umask 0022

# Start pe-httpd in the C locale by default.
HTTPD_LANG=${HTTPD_LANG-"C"}

# This will prevent initlog from swallowing up a pass-phrase prompt if
# mod_ssl needs a pass-phrase from the user.
INITLOG_ARGS=""

# Set HTTPD=/opt/puppet/sbin/pe-httpd.worker in /etc/sysconfig/pe-httpd to use a server
# with the thread-based "worker" MPM; BE WARNED that some modules may not
# work correctly with a thread-based MPM; notably PHP will refuse to start.

# Path to the apachectl script, server binary, and short-form for messages.
apachectl=/opt/puppet/sbin/apachectl
pehttpd=${HTTPD-/opt/puppet/sbin/pe-httpd.worker}
prog=pe-httpd
pidfile=${PIDFILE-/var/run/pe-httpd.pid}
lockfile=${LOCKFILE-/var/lock/subsys/pe-httpd}
RETVAL=0
echo "pehttpd=$pehttpd"

version_check() {
    if [ ! -f "/opt/puppet/pe_version" -o ! -e "/opt/puppet/bin/facter" ] ; then
        return
    fi
    agent_version=`cat /opt/puppet/pe_version`
    product_name='pe-master'
    os=`/opt/puppet/bin/facter operatingsystem operatingsystemrelease | sed -e 's/=>//g' | awk '{print $NF}' | xargs | sed -e 's/ /%20/g'`
    host='updates.puppetlabs.com'
    port='80'
    format='txt'
    URL="http://${host}:${port}/?product=${product_name}&version=${agent_version}&os=${os}&format=txt"
    URLPATH="http://${host}:${port}/?product=${product_name}&version=${agent_version}&os=${os}&format=txt"
    unset -v response i
    if ! ( which curl >/dev/null 2>&1) ; then
        exec 3<>/dev/tcp/${host}/${port}
        echo -e "GET /${URLPATH} HTTP/1.1\r\nUser-agent: bash PuppetLabs checker 0.1\r\nHost: ${host}\r\nConnection: close\r\n\r\n" >&3
        while IFS= read -r; do
            response[i++]=$REPLY
        done <&3
        [[ $REPLY ]] && response[i++]=$REPLY
    else
        while IFS= read -r; do
            response[i++]=$REPLY
        done < <( curl --connect-timeout 10 --silent "${URL}")
        [[ $REPLY ]] && response[i++]=$REPLY
    fi

    if [[ "${response[@]}"  =~ newer=true ]] ; then
        for n in ${!response[@]}; do
            line=${response[$n]}
            if [[ $line =~ message= ]] ; then
                message=${line/*message=/}
                continue
            fi
            if [[ $line =~ link= ]] ;  then
                link=${line/link=/}
                continue
            fi
        done
        if [ "x${message}" != 'x' -a "x${link}" != 'x' ] ; then
            message="${message} (currently ${agent_version})."
            echo "${message}"
            echo "${link}"
            logger -t puppet-master "${message}"
            logger -t puppet-master "${link}"
        else
            echo "There's a newer version of ${product_name} available, but there was an internal problem."
        fi
    fi
}

# The semantics of these two functions differ from the way apachectl does
# things -- attempting to start while running is a failure, and shutdown
# when not running is also a failure.  So we just do it the way init scripts
# are expected to behave here.
start() {
    # if certificates do not exist, then generate
    if [ ! -d /var/opt/lib/pe-puppet/ssl ]; then
      # start puppet master which will generate the certificates
      /opt/puppet/bin/puppet master
      sleep 2
      ps -ef | grep 'puppet master' | grep -v grep | awk '{print $2}' | xargs kill -9
    fi
    echo -n $"Starting $prog: "
    LANG=$HTTPD_LANG daemon --pidfile=${pidfile} $pehttpd $OPTIONS
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && touch ${lockfile}
    # Give passenger time to start
    if [ -z "$q_pe_check_for_updates" ] || [ "${q_pe_check_for_updates}" != "n" ]; then
        version_check &
    fi
    sleep 2
    return $RETVAL
}

# When stopping pe-httpd a delay of >10 second is required before SIGKILLing the
# pe-httpd parent; this gives enough time for the pe-httpd parent to SIGKILL any
# errant children.
stop() {
    echo -n $"Stopping $prog: "
    if [ -s ${pidfile} ]; then
      killproc -p ${pidfile} -d 10 $pehttpd
    else
      killproc -d 10 $pehttpd
    fi
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && rm -f ${lockfile} ${pidfile}
}
reload() {
    echo -n $"Reloading $prog: "
    if ! LANG=$HTTPD_LANG $pehttpd $OPTIONS -t >&/dev/null; then
        RETVAL=6
        echo $"not reloading due to configuration syntax error"
        failure $"not reloading $pehttpd due to configuration syntax error"
    else
        # Force LSB behaviour from killproc
        if [ -s ${pidfile} ]; then
          LSB=1 killproc -p ${pidfile} $pehttpd -HUP
        else
          LSB=1 killproc $pehttpd -HUP
        fi
        RETVAL=$?
        if [ $RETVAL -eq 7 ]; then
            failure $"pe-httpd shutdown"
        fi
    fi
    echo
}

# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  status)
    if [ -s ${pidfile} ]; then
      status -p ${pidfile} $pehttpd
      RETVAL=$?
    else
      if ( pgrep $prog > /dev/null); then
        status $pehttpd
        RETVAL=4
      else
        status $pehttpd
        RETVAL=$?
      fi
    fi
    ;;

  restart)
	stop
	start
	;;
  condrestart|try-restart)
	if status -p ${pidfile} $pehttpd >&/dev/null; then
		stop
		start
	fi
	;;
  force-reload|reload)
        reload
	;;
  graceful|help|configtest|fullstatus)
	$apachectl $@
	RETVAL=$?
	;;
  *)
	echo $"Usage: $prog {start|stop|restart|condrestart|try-restart|force-reload|reload|status|fullstatus|graceful|help|configtest}"
	RETVAL=2
esac

exit $RETVAL
