#!/usr/bin/env bash
if [[ -z "$1" ]]; then
    export phpvers=master
    export phpverscheckout=master
else
    export phpvers=$1
    export phpverscheckout=tags/php-$phpvers
fi
if [[ -z "$2" ]]; then
    export threadsafe=nts
else
    export threadsafe=$2
fi
cd /root/php-src
git fetch --all --tags
git pull origin master
git checkout $phpverscheckout
./buildconf --force
export configoptions='--prefix=/usr --sysconfdir=/etc --localstatedir=/var --datadir=/usr/share/php --mandir=/usr/share/man --enable-fpm --with-fpm-user=apache --with-fpm-group=apache --with-config-file-path=/etc --with-zlib --enable-bcmath --with-bz2 --enable-calendar --enable-dba=shared --with-gdbm --with-gmp --enable-ftp --with-gettext=/usr --enable-mbstring --with-readline --with-mysql-sock=/run/mysqld/mysqld.sock --with-curl --with-openssl --with-openssl-dir=/usr --with-mhash --enable-intl --with-sodium=/usr --with-libxml-dir=/usr --with-libdir=/lib64 --enable-sockets --enable-libxml --enable-soap --with-gd --with-jpeg-dir=/usr --with-png-dir=/usr --with-zlib-dir=/usr --with-freetype-dir=/usr --enable-exif --with-xsl --with-xmlrpc --with-pgsql --with-pdo-mysql=/usr --with-pdo-pgsql --with-mysqli --with-ldap --with-ldap-sasl'
if [[ "$phpvers" == "5."* || "$phpvers" == "7.0."* || "$phpvers" == "7.1."* ]]; then
export configoptionscrypt=' --with-mcrypt=/usr'
else
export configoptionscrypt=' --with-sodium=/usr'
fi
if [[ "$phpvers" == "5."* || "$phpvers" == "7.0."* || "$phpvers" == "7.1."* || "$phpvers" == "7.2."* ]]; then
export configoptionszip=' --enable-zip'
else
export configoptionszip=''
fi
if [[ "$threadsafe" == "zts" ]]; then
export configoptionsts=' --enable-opcache --enable-maintainer-zts --enable-pthreads'
else
export configoptionsts=' --enable-opcache'
fi
export configoptions=$configoptions$configoptionscrypt$configoptionszip$configoptionsts
./configure $configoptions
make
make install
install -v -m644 php.ini-production /etc/php.ini &&
mv -v /etc/php-fpm.conf{.default,} &&
install -v -m755 -d /usr/share/doc/php-"$phpvers" &&
install -v -m644 CODING_STANDARDS EXTENSIONS INSTALL NEWS README* UPGRADING* php.gif \
/usr/share/doc/php-"$phpvers" &&
ln -v -sfn /usr/lib/php/doc/Archive_Tar/docs/Archive_Tar.txt \
/usr/share/doc/php-"$phpvers" &&
ln -v -sfn /usr/lib/php/doc/Structures_Graph/docs \
/usr/share/doc/php-"$phpvers" &&
cp -v /etc/php-fpm.d/www.conf.default /etc/php-fpm.d/www.conf
sed -i 's@php/includes"@&\ninclude_path = ".:/usr/lib/php"@' \
/etc/php.ini
sed -i -e '/proxy_module/s/^#//' \
-e '/proxy_fcgi_module/s/^#//' \
/etc/httpd/httpd.conf
echo \
'#ProxyPassMatch ^/(.*\.php)$ fcgi://127.0.0.1:9000/srv/www/$1' >> \
/etc/httpd/httpd.conf
cat >>/etc/php.ini << EOF
[OpCache]
zend_extension = $( php -i | grep extensions | awk '{print $3}' )/opcache.so
EOF
sed -i -e '/proxy_module/s/^#//' -e '/proxy_fcgi_module/s/^#//' /etc/httpd/httpd.conf
cat >>/etc/httpd/httpd.conf << 'EOF'
<Proxy "unix:/run/php-fpm.sock|fcgi://localhost/">
    ProxySet min=0
    ProxySet timeout=1800
</Proxy>

<FilesMatch \.php$>
    # 2.4.10+ can proxy to unix socket
    SetHandler "proxy:unix:/run/php-fpm.sock|fcgi://localhost/"

    # Else we can just use a tcp socket:
    # SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>
EOF
sed -i 's/#LoadModule rewrite_module/LoadModule rewrite_module/' /etc/httpd/httpd.conf
sed -i 's/AllowOverride None/AllowOverride All/' /etc/httpd/httpd.conf
sed -i 's/DirectoryIndex index.html/DirectoryIndex index.php index.html/' /etc/httpd/httpd.conf
sed -i 's/listen = 127.0.0.1:9000/; listen = 127.0.0.1:9000\nlisten = \/run\/php-fpm.sock/' /etc/php-fpm.d/www.conf
cat >/etc/init.d/php-fpm << 'EOF'
#! /bin/sh
#######################################################################
# Begin /etc/init.d/php-fpm
#
# Description : Start the PHP fastCGI Proces Manager
#
# Author      : P Labastie - pierre.labastie@neuf.fr
#               from a file shipped with the PHP pacakge
#
# Version     : LFS 7.5
#
########################################################################

### BEGIN INIT INFO
# Provides:          php-fpm
# Required-Start:    $syslog $local_fs $network
# Should-Start:      $remote_fs
# Required-Stop:     $network
# Should-Stop:       $remote_fs
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 6
# Short-Description: starts php-fpm
# Description:       starts the PHP FastCGI Process Manager daemon
# X-LFS-Provided-By: BLFS / LFS 7.5
### END INIT INFO

. /lib/lsb/init-functions

#$LastChangedBy: pierre $
#$Date: 2014-03-29 04:48:53 -0500 (Sat, 29 Mar 2014) $

prefix=/usr
exec_prefix=${prefix}

php_fpm_BIN=${exec_prefix}/sbin/php-fpm
php_fpm_CONF=/etc/php-fpm.conf
php_fpm_PID=/var/run/php-fpm.pid


php_opts="--fpm-config $php_fpm_CONF --pid $php_fpm_PID"


wait_for_pid () {
	try=0

	while test $try -lt 35 ; do

		case "$1" in
			'created')
			if [ -f "$2" ] ; then
				try=''
				break
			fi
			;;

			'removed')
			if [ ! -f "$2" ] ; then
				try=''
				break
			fi
			;;
		esac

		echo -n .
		try=`expr $try + 1`
		sleep 1

	done

}

case "$1" in
	start)
		log_info_msg "Starting PHP fastCGI Process Manager..."

		start_daemon $php_fpm_BIN --daemonize $php_opts

		if [ "$?" != 0 ] ; then
			log_failure_msg2
			exit
		fi

		wait_for_pid created $php_fpm_PID

		if [ -n "$try" ] ; then
			log_failure_msg2
		else
			log_success_msg2
		fi
	;;

	stop)
		log_info_msg "Stopping PHP fastCGI Process Manager..."

		if [ ! -r $php_fpm_PID ] ; then
			log_warning_msg "php-fpm not running?"
			exit
		fi

		killproc -p $php_fpm_PID $php_fpm_BIN -QUIT

		wait_for_pid removed $php_fpm_PID

		if [ -n "$try" ] ; then
			log_failure_msg2
		else
			log_success_msg2
		fi
	;;

	status)
		statusproc $php_fpm_BIN
	;;

	restart)
		$0 stop
		$0 start
	;;

	reload)

		log_info_msg "Reload service php-fpm..."
		killproc -p $php_fpm_PID $php_fpm_BIN -USR2
		log_success_msg2
	;;

	*)
		echo "Usage: $0 {start|stop|restart|reload|status}"
		exit 1
	;;

esac
EOF
chmod +x /etc/init.d/php-fpm
ln -sf  ../init.d/php-fpm /etc/rc.d/rc0.d/K28php-fpm
ln -sf  ../init.d/php-fpm /etc/rc.d/rc1.d/K28php-fpm
ln -sf  ../init.d/php-fpm /etc/rc.d/rc2.d/K28php-fpm
ln -sf  ../init.d/php-fpm /etc/rc.d/rc3.d/S32php-fpm
ln -sf  ../init.d/php-fpm /etc/rc.d/rc4.d/S32php-fpm
ln -sf  ../init.d/php-fpm /etc/rc.d/rc5.d/S32php-fpm
ln -sf  ../init.d/php-fpm /etc/rc.d/rc6.d/K28php-fpm
/etc/init.d/mysql start
/etc/init.d/php-fpm start
chown apache:apache /run/php-fpm.sock
/etc/init.d/httpd start
