#!/usr/bin/env bash

set -e # exit immediately if a simple command exits with a non-zero status
set -u # report the usage of uninitialized variables

# Detect # of CPUs so make jobs can be parallelized
CPUS=$(grep -c ^processor /proc/cpuinfo)
 # Available variables
# $BOSH_COMPILE_TARGET - where this package & spec'd source files are available
# $BOSH_INSTALL_TARGET - where you copy/install files to be included in package
export HOME=/var/vcap

# from http://zlib.net/zlib-1.2.8.tar.gz
echo "Extracting zlib ... "
tar xzvf nginx/zlib-1.2.8.tar.gz
export ZLIB_SRC=${BOSH_COMPILE_TARGET}/zlib-1.2.8

# from https://www.openssl.org/source/openssl-1.0.2h.tar.gz
echo "Extracting openssl ... "
tar xvf nginx/openssl-1.0.2h.tar.gz
export OPENSSL_SRC=${BOSH_COMPILE_TARGET}/openssl-1.0.2h

# from ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.39.tar.gz
echo "Extracting pcre..."
tar xzvf nginx/pcre-8.39.tar.gz

# from https://github.com/openresty/headers-more-nginx-module/archive/v0.30.tar.gz
echo "Extracting headers-more module..."
tar xzvf nginx/headers-more-nginx-module-0.30.tar.gz

# from http://nginx.org/download/nginx-1.10.1.tar.gz
echo "Extracting nginx..."
tar xzvf nginx/nginx-1.10.1.tar.gz

echo "Building nginx..."
export OPENSSL_LIB=/var/vcap/packages/nginx/lib
export ZLIB_LIB=/var/vcap/packages/nginx/lib

pushd nginx-1.10.1
    ./configure \
    --with-cc-opt="-Wno-error" \
    --user=vcap --group=vcap \
    --prefix=${BOSH_INSTALL_TARGET} \
    --with-ld-opt="-Wl,-rpath,$OPENSSL_LIB,-rpath,$ZLIB_LIB" \
    --with-pcre=../pcre-8.39 \
    --with-pcre-jit \
    --with-zlib=${ZLIB_SRC} \
    --with-openssl=${OPENSSL_SRC} \
    --add-module=../headers-more-nginx-module-0.30 \
    --with-http_realip_module \
    --with-http_ssl_module
    make -j $CPUS install
popd
