#!/bin/bash
acceptVersion nginx $1
shift

local NGINX_MODS=(pcre http_ssl_module http_gzip_static_module http_stub_status_module)
local NGINX_VERSION=${APP_VERSIONS[nginx]}

[[ ! $NGINX_VERSION ]] && abort "nginx version not specified"

# if we have version 1.4.1 or greater include additional default mods
if [[ '1.4.1' == `echo -e "1.4.1\n$NGINX_VERSION" | sort -V | head -n1` ]]; then
	NGINX_MODS=( ${NGINX_MODS[@]} http_spdy_module http_gunzip_module)
fi

# initialise the nginx source
NGINX_SOURCE=http://nginx.org/download/nginx-$NGINX_VERSION.tar.gz

# if we have additional options, specify mods
[[ $@ ]] && NGINX_MODS=$@

function installNginx {

	local maxmods=(${#NGINX_MODS[@]} - 1)
	local ii
	local nginx_compile_opts=()

	for ((ii = 0; ii <= maxmods; ii++)); do
		if [[ ${NGINX_MODS[ii]} ]]; then
			nginx_compile_opts[ii]=--with-${NGINX_MODS[ii]}
		fi
	done

	require packages build-essential libpcre3 libpcre3-dev libpcrecpp0 libssl-dev zlib1g-dev	

	log "Installing Nginx $NGINX_VERSION";

	fetchSource $NGINX_SOURCE
	cd $BASHINATE_SOURCE/nginx-$NGINX_VERSION

	# configure nginx
	log "- configuring"
	./configure --prefix=$BASHINATE_INSTALL/nginx/$NGINX_VERSION ${nginx_compile_opts[@]} \
		|| (echo "!!! Nginx source configuration failed" & exit 1)

	# make nginx and install
	log "- compiling and installing"
	make && make install \
		|| (echo "!!! Nginx build failed" & exit 1)
}

# if we don't have nginx installed, then install
log "Checking Nginx version $NGINX_VERSION installed"
if [ ! -e $BASHINATE_INSTALL/nginx/$NGINX_VERSION ]
then
	installNginx
fi

# if the www directory doesn't exist then install a placeholder
if [ ! -d $BASHINATE_INSTALL/www ]; then
	require nginx-bootstrap
fi

# TODO: test nginx
