#!/bin/zsh
_nginx_ver_latest=1.15.1
_nginx_ver_stable=1.14.0
_nginx_ver_nopool=1.13.8
_nginx_ver_legacy=1.8.1
_nginx_ver_old=1.6.3
_nginx_ver_very_old=0.8.55
_ngx_echo_module_ver=0.60
_lua_nginx_module_ver=0.10.13
_lua_upstream_nginx_module_ver="0.06"
_openresty_ver=1.13.6.2

_target_module_name=nchan

pkgname=nginx-${_target_module_name}-dev-git

if [[ -n $OPENRESTY_CUSTOM_VERSION ]]; then
  _openresty_ver=$OPENRESTY_CUSTOM_VERSION
fi

OPTIONS=(!strip debug docs libtool staticlibs emptydirs zipman purge !upx)
if [[ -z $NO_DEBUG ]]; then
  #debug build. clear cflags
  CFLAGS=" -ggdb -fvar-tracking-assignments -O$OPTIMIZE_LEVEL"
fi

CFLAGS="$CFLAGS -Wno-error -Wno-implicit-fallthrough -Wall -Wextra -Wno-unused-parameter -Wpointer-sign -Wpointer-arith -Wshadow -Wnested-externs -Wsign-compare"
if [[ $SANITIZE_UNDEFINED == 1 ]]; then
    CFLAGS="$CFLAGS -fsanitize=undefined -fsanitize=shift -fsanitize=integer-divide-by-zero -fsanitize=unreachable -fsanitize=vla-bound -fsanitize=null -fsanitize=return -fsanitize=bounds -fsanitize=alignment -fsanitize=object-size -fsanitize=float-divide-by-zero -fsanitize=float-cast-overflow -fsanitize=nonnull-attribute -fsanitize=returns-nonnull-attribute -fsanitize=enum -lubsan"
fi
_include_http2=0

_semver_gteq() {
  ruby -rrubygems -e "exit Gem::Version.new(('$1').match(/\/?([.\d]+)/)[1]) < Gem::Version.new(('$2').match(/^[^\s+]/)) ? 0 : 1"
  return $?
}

if [[ $NO_POOL == 1 ]] && [[ -z $USE_OPENRESTY ]]; then
  _nginx_ver=$_nginx_ver_nopool
elif [[ $NGINX_LEGACYVERSION == 1 ]]; then
  _nginx_ver=$_nginx_ver_legacy
elif [[ $NGINX_OLDVERSION == 1 ]]; then
  _nginx_ver=$_nginx_ver_old
elif [[ $NGINX_VERYOLDVERSION == 1 ]]; then
  _nginx_ver=$_nginx_ver_very_old
elif [[ $NGINX_STABLEVERSION == 1 ]]; then
  _nginx_ver=$_nginx_ver_stable
elif [[ -n $NGINX_CUSTOM_VERSION ]]; then
  _nginx_ver=$NGINX_CUSTOM_VERSION
else
  _nginx_ver=$_nginx_ver_latest
fi

if [[ -n $_nginx_ver ]]; then
  if (_semver_gteq $_nginx_ver 1.9.5); then
    _include_http2=1
  elif (_semver_gteq $_nginx_ver 1.3.15); then
    _include_spdy=1
  fi
  _nginx_git_source_fragment="#tag=release-${_nginx_ver}"
else
  #using master
  _include_http2=1
fi

_pkgname="nginx"
PKGEXT=".pkg.tar"

_user="http"
_group="http"
_doc_root="/usr/share/${_pkgname}/http"
_tmp_path="/tmp"
_pid_path="/run"
_lock_path="/var/lock"
_access_log="/dev/stdout"
_error_log="errors.log"
_target_module_dir="${startdir}/${_target_module_name}"

_pkgver() {
  pushd "$_target_module_dir" >/dev/null
  printf "%s.%s.%s.%s" "$_nginx_ver" "$(git rev-parse --abbrev-ref HEAD | sed -r 's/-/_/g')" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
  popd >/dev/null
}

pkgver=0
pkgrel=1
pkgdesc="Nginx + ngx_lua_ipc"
arch=('any')
install=install


makedepends=('ruby')
depends=('pcre' 'zlib' 'openssl')
url="http://nginx.org"
license=('custom')
conflicts=('nginx' 'nginx-mainline' 'nginx-devel') 
provides=('nginx' 'nginx-custom')

if [[ -n $USE_OPENRESTY ]]; then
  _name="openresty"
else
  _name="nginx"
fi


if [[ -z $DEFAULT_PREFIX ]]; then
  if [[ -n $CUSTOM_PREFIX ]]; then
    _prefix_path=$CUSTOM_PREFIX
  else
    _prefix_path="/etc/$_name"
  fi
else
  _prefix_path="/usr/local/$_name"
fi

if [[ -n $USE_OPENRESTY ]]; then
  _conf_path="${_prefix_path:1}/nginx"
else
  _conf_path="${_prefix_path:1}"
fi

_nginxconf_path="${_conf_path}/conf/nginx.conf"

backup=("${_nginxconf_path}"
  "${_conf_path}/conf/koi-win"
  "${_conf_path}/conf/koi-utf"
  "${_conf_path}/conf/win-utf"
  "${_conf_path}/conf/mime.types"
  "${_conf_path}/conf/fastcgi.conf"
  "${_conf_path}/conf/fastcgi_params"
  "${_conf_path}/conf/scgi_params"
  "${_conf_path}/conf/uwsgi_params"
  "etc/logrotate.d/nginx")
_user=http
_group=http

_nginx_source="http://nginx.org/download/nginx-${_nginx_ver}.tar.gz"

_openresty_source="https://openresty.org/download/openresty-${_openresty_ver}.tar.gz"

_nginx_git_source="git+https://github.com/nginx/nginx.git${_nginx_git_source_fragment}"

_no_pool_patch_source="https://raw.github.com/shrimp/no-pool-nginx/master/nginx-${_nginx_ver_nopool}-no_pool.patch"

if [[ $_lua_nginx_module_ver == "master" ]]; then
  _lua_nginx_module_url="git+https://github.com/openresty/lua-nginx-module.git"
else
  _lua_nginx_module_url="https://github.com/openresty/lua-nginx-module/archive/v${_lua_nginx_module_ver}.tar.gz"
fi

_lua_upstream_nginx_module_url="https://github.com/openresty/lua-upstream-nginx-module/archive/v${_lua_upstream_nginx_module_ver}.tar.gz"
_ngx_debug_pool_url="https://github.com/chobits/ngx_debug_pool.git"
_ngx_echo_module="https://github.com/openresty/echo-nginx-module/archive/v${_ngx_echo_module_ver}.tar.gz"

_lua_stream_module_ver=0.0.1
_lua_stream_module_src="https://github.com/openresty/stream-lua-nginx-module/archive/v${_lua_stream_module_ver}.tar.gz"

if [[ -n $USE_OPENRESTY ]]; then
  _source=$_openresty_source
  _extracted_dir="openresty-${_openresty_ver}"  
else
  if [[ -n $NO_MAKEPKG ]]; then
    _source=$_nginx_source
      _extracted_dir="nginx-${_nginx_ver}"
  else
    _source=$_nginx_git_source
    _extracted_dir="nginx"
  fi
fi

source=("$_source"
  "nginx.conf"
  "nginx.logrotate"
  "nginx.service"
  "git+${_ngx_debug_pool_url}"
  "bl.txt"
)

md5sums=('SKIP'
         '1fe7a3ca0773ce13f9f92e239a99f8b9'
         'ab1eb640c978536c1dad16674d6b3c3c'
         '62d494d23aef31d0b867161f9fffa6eb'
         'SKIP'
	 'SKIP')

if [[ -n $WITH_LUA_STREAM_MODULE ]]; then
  source+=( "$_lua_stream_module_src" )
  md5sums+=( 'SKIP')
fi

if [[ $WITH_NGX_ECHO_MODULE == 1 ]]; then
  source+=(  "$_ngx_echo_module" )
  md5sums+=( 'SKIP' )
fi

if [[ -n $WITH_LUA_MODULE ]]; then
  source+=( "$_lua_nginx_module_url" "$_lua_upstream_nginx_module_url" )
  md5sums+=( 'SKIP' 'SKIP' )
  
fi

if [[ $NO_POOL == 1 ]] && [[ -z $USE_OPENRESTY ]]; then
  source+=( "$_no_pool_patch_source" )
  md5sums+=( 'SKIP')
fi

if [[ $TRACK_POOL == 1 ]]; then
  source+=("track-pool.patch")
  md5sums+=('SKIP')
fi

build() {
  local _src_dir="${srcdir}/${_extracted_dir}"
  #ln -sfT "$srcdir" "$srcdir/nginx"
  ln -sfT "$startdir/../../" "$srcdir/${_target_module_name}"
  local _build_dir="${_src_dir}/objs"
  cd "$srcdir/${_extracted_dir}"
  
  if [[ -z $USE_OPENRESTY ]]; then
    sed -i.bak '/n == SSL_R_NO_CIPHERS_PASSED/d' src/event/ngx_event_openssl.c
  else
    sed -i.bak '/n == SSL_R_NO_CIPHERS_PASSED/d' bundle/nginx-*/src/event/ngx_event_openssl.c
  fi
  
  if [[ -z $CONTINUE ]] && [[ -z $NO_EXTRACT_SOURCE ]]; then
    if [[ $NO_POOL == 1 ]]; then
      echo "using the no-pool patch"
      if [[ -n $USE_OPENRESTY ]]; then
        pushd bundle
        patch -p0 < "./nginx-no_pool.patch"
        popd
      else
        patch -p1 < "${srcdir}/nginx-${_nginx_ver}-no_pool.patch"
      fi
    fi
    
    if [[ $TRACK_POOL == 1 ]]; then
      echo "using the track-pool patch"
      if [[ -n $USE_OPENRESTY ]]; then
        echo "track_pool patch not available for openresty"
      else
        patch -p1 -F 5 < "${srcdir}/track-pool.patch"
      fi
    fi
    
    if [[ $NGX_SLAB_PATCH == 1 ]]; then
      echo "using the ngx_slab patch to fix large alloc/frees"
      patch -p1 < "${startdir}/ngx_slab.patch"
    fi
    if [[ $NGX_DEBUG_POOL == 1 ]]; then
      echo "patch nginx to debug pools"
      patch -p1 < "${srcdir}/ngx_debug_pool/debug_pool.patch"
    fi
  fi

  if [[ $MUDFLAP == 1 ]]; then
    export CFLAGS="$CFLAGS -fmudflap"
  fi

  CFLAGS="${CFLAGS/-Werror/}" #no warning-as-error
  
  CONFIGURE=()
  
  if [[ -n $EXTRA_CONFIG_OPT ]]; then
    if [[ $0 == "/usr/bin/makepkg" ]]; then
      CONFIGURE+=${EXTRA_CONFIG_OPT}
    else
      CONFIGURE+=( ${=EXTRA_CONFIG_OPT} )
    fi    
  fi
  
  if [[ -z $DEFAULT_PREFIX ]]; then
    CONFIGURE+=( --prefix=$_prefix_path )
  fi
  
  CONFIGURE+=(
    --sbin-path=/usr/bin/nginx
    --pid-path=${_pid_path}/nginx.pid
    --lock-path=${_pid_path}/nginx.lock
    --http-client-body-temp-path=${_tmp_path}/client_body_temp
    --http-proxy-temp-path=${_tmp_path}/proxy_temp
    --http-fastcgi-temp-path=${_tmp_path}/fastcgi_temp
    --http-uwsgi-temp-path=${_tmp_path}/uwsgi_temp
    --http-log-path=${_access_log}
    --error-log-path=${_error_log}
  )

  if [[ -n $WITH_HTTP_SSL ]]; then
    CONFIGURE+=( --with-http_ssl_module )
  fi
    
  if [[ -n $WITH_STREAM_MODULE ]]; then
    CONFIGURE+=( --with-stream )
  fi

  if [[ -n $WITH_STUB_STATUS_MODULE ]]; then
    CONFIGURE+=( --with-http_stub_status_module )
  fi
  
  if [[ -n $WITH_LUA_STREAM_MODULE ]]; then
    CONFIGURE+=( --add-module=../stream-lua-nginx-module-${_lua_stream_module_ver} )
  fi

  if [[ -n $WITH_LUA_MODULE ]]; then
    if [[ $_lua_nginx_module_ver == "master" ]]; then
      CONFIGURE+=( "--add-module=${srcdir}/lua-nginx-module")
    else
      CONFIGURE+=( "--add-module=${srcdir}/lua-nginx-module-${_lua_nginx_module_ver}")
    fi
    CONFIGURE+=("--add-module=${srcdir}/lua-upstream-nginx-module-${_lua_upstream_nginx_module_ver}")
  fi

  if [[ $DYNAMIC == 1 ]]; then
    CONFIGURE+=( --add-dynamic-module=../${_target_module_name} )
  else
    CONFIGURE+=( --add-module=../${_target_module_name} )
  fi

  if [[ $CONFIGURE_WITH_DEBUG == 1 ]]; then
    CONFIGURE+=( "--with-debug" )
  fi
  
  if [[ -z $NO_NGINX_USER ]]; then
    CONFIGURE+=( "--user=${_user}" "--group=${_group}" )
  fi
    
  if [[ $_include_http2 == 1 ]]; then
    CONFIGURE+=( "--with-http_v2_module" )
  fi
  
  if [[ $_include_spdy == 1 ]]; then
    CONFIGURE+=( "--with-http_spdy_module" )
  fi
    
  if [[ $NGX_DEBUG_POOL == 1 ]]; then
    CONFIGURE+=( "--add-module=../ngx_debug_pool" )
  fi

  if [[ $WITH_NGX_ECHO_MODULE == 1 ]]; then
    CONFIGURE+=( "--add-module=../echo-nginx-module-${_ngx_echo_module_ver}")
  fi
  
  if [[ -z $NGINX_VERYOLDVERSION ]]; then
    CONFIGURE+=( "--http-scgi-temp-path=${_tmp_path}/scgi_temp" )
  fi

  if [[ $SANITIZE_UNDEFINED == 1 ]]; then
    CONFIGURE+=("--with-ld-opt=-lubsan")
  fi

  
  if [[ $CC == *clang* ]] || [[ "$OSTYPE" == "darwin"* ]]; then
    #not a valid clang parameter
    CFLAGS="${CFLAGS/-fvar-tracking-assignments/}"
    CFLAGS="${CFLAGS/-fvar-tracking-assignments/}"
    if [[ -z $CLANG_ANALYZER ]]; then
      CFLAGS="-ferror-limit=5 $CFLAGS -Wconditional-uninitialized"
    fi
  elif [[ $CC == "cc" ]] || [[ $CC == "gcc" ]] || [[ -z $CC ]] && [[ -z $NO_GCC_COLOR ]]; then
    CFLAGS="-fdiagnostics-color=always  -Wmaybe-uninitialized $CFLAGS"
  fi
  
  echo $CFLAGS
  export CCACHE_CPP2=yes
  if ! [[ -z $CLANG_ANALYZER ]]; then
    scan-build -o "$CLANG_ANALYZER" ./configure ${CONFIGURE[@]}
    scan-build -o "$CLANG_ANALYZER" make -j4
  elif ! [[ -z $CONTINUE ]]; then
    make $REMAKE
  else
    ln -svf $srcdir/bl.txt
    
    if [[ ! -f ./configure ]]; then
      ln -s auto/configure ./
    fi
    
    if [[ -n $USE_OPENSSL_10 ]]; then
      CFLAGS="-I/usr/include/openssl-1.0/ $CFLAGS"
      LDFLAGS="-L/usr/lib/openssl-1.0/ $LDFLAGS"
    fi
    
    if [[ -n $EXPLICIT_CFLAGS ]]; then
      echo "./configure ${CONFIGURE[@]} --with-cc-opt=${CFLAGS} --with-ld-opt=${LDFLAGS}"
      ./configure ${CONFIGURE[@]} "--with-cc-opt=${CFLAGS}" "--with-ld-opt=${LDFLAGS}"
    else
      ./configure ${CONFIGURE[@]}
    fi
    
    
    #ln -sf ${srcdir}/lua-nginx-module-${_lua_nginx_module_ver}/src ../ngx_lua_ipc/src/lua-nginx-module-source > /dev/null
    
    if [[ $? == 0 ]]; then
      make
    else
      exit 1
    fi
  fi
}

package() {
  echo "make install"
  cd "${srcdir}/${_extracted_dir}"
  make DESTDIR="$pkgdir/" install >/dev/null
  sed -i -e "s/\<user\s\+\w\+;/user $_user;/g" $pkgdir/${_nginxconf_path}
  install -d "${pkgdir}/${_tmp_path}" 
  install -d "${pkgdir}/${_doc_root}" 
    
  mv "${pkgdir}/${_conf_path}/html/"* "${pkgdir}/${_doc_root}"
  rm -rf "${pkgdir}/${_conf_path}/html"
  
  
  #install -D -m644 "${srcdir}/nginx.logrotate" "${pkgdir}/etc/logrotate.d/${_pkgname}" #no default logrotate.
  install -D -m644 "${srcdir}/nginx.conf" "${pkgdir}/etc/conf.d/nginx"
  install -D -m644 "${srcdir}/nginx.service" "${pkgdir}/lib/systemd/system/nginx.service"
  #install -D -m644 "LICENSE" "${pkgdir}/usr/share/licenses/nginx/LICENSE"
  #if [[ -z $NGINX_VERYOLDVERSION ]]; then
  #  install -D -m644 "man/nginx.8" "${pkgdir}/usr/share/man/man8/nginx.8"
  #fi
}
