#!/bin/bash

#if [[ "$EUID" -ne 0 ]]; then
#	echo -e "Sorry, you need to run this as root"
#	exit 1
#fi

BASE_DIR=$(dirname $0)
if [ $BASE_DIR == "." ] ; then
    SCRIPT_DIR=$(pwd)
else
    SCRIPT_DIR=$(pwd)/$BASE_DIR
fi

# Variables
INSTALL_USER=`whoami`
INSTALL_DIR=$1

SOURCE_DIR=${SCRIPT_DIR}/source_files

NGINX_VERSION=1.15.8
NGINX_INSTALL_FILE=nginx-${NGINX_VERSION}

INSTALL_DATE=`date +%Y%m%d_%H%M%S`


if [ "x$1" = "x" ]; then
    echo "#################################################"
    echo "[ERROR] input install directory" >> install.log.$INSTALL_DATE
    echo "[ERROR] input install directory" 
    echo "#################################################"
    echo "[ INSTALL_HOME ] is $SCRIPT_DIR"
    INSTALL_DIR=$SCRIPT_DIR
fi

clear


# Cleanup
# The directory should be deleted at the end of the script, but in case it fails
#rm -r /usr/local/src/nginx/ >> /dev/null 2>&1
mkdir -p ${INSTALL_DIR}/conf.d
mkdir -p ${INSTALL_DIR}/modules
mkdir -p ${INSTALL_DIR}/tmp/client
mkdir -p ${INSTALL_DIR}/tmp/proxy
mkdir -p ${INSTALL_DIR}/tmp/fastcgi

# Dependencies
#apt-get update
#apt-get install -y build-essential ca-certificates wget curl libpcre3 libpcre3-dev autoconf unzip automake libtool tar git libssl-dev zlib1g-dev uuid-dev lsb-release

sudo yum install -y pcre-devel zlib


echo "SCRIPT_DIR=$SCRIPT_DIR"
echo "SOURCE_DIR=$SOURCE_DIR"
echo "INSTALL_DIR=$INSTALL_DIR"

cd $SOURCE_DIR
tar -xvzf ${NGINX_INSTALL_FILE}.tar.gz || exit 1

NGINX_OPTIONS="
	--prefix=${INSTALL_DIR} \
	--http-client-body-temp-path=${INSTALL_DIR}/tmp/client \
	--http-proxy-temp-path=${INSTALL_DIR}/tmp/proxy \
	--http-fastcgi-temp-path=${INSTALL_DIR}/tmp/fastcgi \
	--http-scgi-temp-path=${INSTALL_DIR}/tmp/scgi \
	--http-uwsgi-temp-path=${INSTALL_DIR}/tmp/uwsgi \
	--user=${INSTALL_USER} \
	--group=${INSTALL_USER} \
	--with-cc-opt=-Wno-deprecated-declarations"

NGINX_MODULES="--with-http_ssl_module \
	--with-http_realip_module \
	--with-http_addition_module \
	--with-http_sub_module \
	--with-http_dav_module \
	--with-http_flv_module \
	--with-http_mp4_module \
	--with-http_gunzip_module \
	--with-http_gzip_static_module \
	--with-http_random_index_module \
	--with-http_secure_link_module \
	--with-http_stub_status_module \
	--with-http_auth_request_module \
	--with-threads \
	--with-stream \
	--with-stream_ssl_module \
	--with-http_slice_module \
	--with-mail \
	--with-mail_ssl_module \
	--with-file-aio \
	--with-http_v2_module \
	--with-ipv6"


##############################################################

cd $SOURCE_DIR/${NGINX_INSTALL_FILE}

./configure $NGINX_OPTIONS $NGINX_MODULES
make -j "$(nproc)"
make install


############ Default Template Copy ##############
cp -fR $SOURCE_DIR/sbin/* ${INSTALL_DIR}/sbin/
cp -fR $SOURCE_DIR/conf/* ${INSTALL_DIR}/conf/
cp -fR $SOURCE_DIR/conf.d/* ${INSTALL_DIR}/conf.d/



############ Nginx Server Directory Replace ########
#${SCRIPT_DIR}/nginx-replace.sh ${INSTALL_DIR}



############ Nginx Directory Replace ########
