FROM nginx:1.18.0 as downloader

ARG NGINX_VERSION=1.18.0

ARG REVISION
ARG BUILDTIME
LABEL REVISION=${REVISION}
LABEL BUILDTIME=${BUILDTIME}

# Install nginx-opentracing
RUN apt-get update && \
  apt-get install -y wget && \
  get_latest_release() { \
  wget -qO- "https://api.github.com/repos/$1/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/'; \
  } && \
  OPENTRACING_NGINX_VERSION="$(get_latest_release opentracing-contrib/nginx-opentracing)" && \
  DD_OPENTRACING_CPP_VERSION="$(get_latest_release DataDog/dd-opentracing-cpp)" && \
  \
  wget https://github.com/opentracing-contrib/nginx-opentracing/releases/download/${OPENTRACING_NGINX_VERSION}/linux-amd64-nginx-${NGINX_VERSION}-ngx_http_module.so.tgz && \
  NGINX_MODULES=$(nginx -V 2>&1 | grep "configure arguments" | sed -n 's/.*--modules-path=\([^ ]*\).*/\1/p') && \
  tar zxvf linux-amd64-nginx-${NGINX_VERSION}-ngx_http_module.so.tgz -C "${NGINX_MODULES}" && \
  ls -la ${NGINX_MODULES} && \
  # Install Datadog module
  wget -O - https://github.com/DataDog/dd-opentracing-cpp/releases/download/${DD_OPENTRACING_CPP_VERSION}/linux-amd64-libdd_opentracing_plugin.so.gz | gunzip -c > /usr/local/lib/libdd_opentracing_plugin.so

COPY nginx.conf.template /usr/share/nginx/nginx.conf.template
COPY dd-config.json.template /usr/share/nginx/dd-config.json.template

# Set default variables
ENV HEALTHCHECK_PATH="/health" \
    ACCESS_LOG_STATUS="/var/log/nginx/access.log combined" \
    PROXY_BUFFERS="8 32k" \
    PROXY_BUSY_BUFFERS_SIZE="32k" \
    PROXY_BUFFER_SIZE="16k" \
    PROXY_CACHE_PATH="/tmp" \
    PROXY_CACHE_KEYS_ZONE="default_zone" \
    PROXY_CACHE_MAX_SIZE="5g" \
    PROXY_CACHE_INACTIVE="10m" \
    SERVER_NAME="_" \
    BACKEND_ADDRESS="example.com" \
    DD_SERVICE="nginx-cache-example" \
    DATACOMPLETENESS_PATH="/v3/data-health/" \
    ADS_PERFOMANCE_ENDPOINT="/v3/ads/performance" \
    ADS_PERFOMANCE_CACHE_INACTIVE="2s" \
    TRACK_POSITIONS_CHARTS_ENDPOINT="/v3/track-positions/charts" \
    TRACK_POSITIONS_CHARTS_CACHE_INACTIVE="15m"

CMD envsubst '$${HEALTHCHECK_PATH},\
  $${PROXY_CACHE_PATH},\
  $${PROXY_CACHE_KEYS_ZONE},\
  $${PROXY_CACHE_MAX_SIZE},\
  $${PROXY_CACHE_INACTIVE},\
  $${SERVER_NAME},\
  $${BACKEND_ADDRESS},\
  $${PROXY_BUFFER_SIZE},\
  $${ACCESS_LOG_STATUS},\
  $${PROXY_BUFFERS},\
  $${PROXY_BUSY_BUFFERS_SIZE},\
  $${DATACOMPLETENESS_PATH},\
  $${ADS_PERFOMANCE_ENDPOINT},\
  $${ADS_PERFOMANCE_CACHE_INACTIVE},\
  $${TRACK_POSITIONS_CHARTS_ENDPOINT},\
  $${TRACK_POSITIONS_CHARTS_CACHE_INACTIVE}'\
  < /usr/share/nginx/nginx.conf.template > /etc/nginx/nginx.conf \
  && envsubst '$${DD_SERVICE}' < /usr/share/nginx/dd-config.json.template > /etc/nginx/dd-config.json \
  && cat /etc/nginx/nginx.conf && exec nginx -g 'daemon off;'
