#!/usr/bin/env bash
# bin/compile <build-dir> <cache-dir>
set -eo pipefail
[[ $TRACE ]] && set -x

# shellcheck source=conf/nginx-configure-flags
source "$(cd "$(dirname "$0")" && cd .. && pwd)/conf/nginx-configure-flags"
NGINX_TARBALL="nginx-${NGINX_VERSION}.tar.gz"
PCRE_TARBALL="pcre2-${PCRE_VERSION}.tar.gz"
ZLIB_TARBALL="zlib-${ZLIB_VERSION}.tar.gz"
BUILDPACK_REPO="dokku/heroku-buildpack-nginx"

suppress() {
  /bin/rm --force /tmp/surpress.out 2>/dev/null
  # shellcheck disable=SC2069
  "$@" 2>&1 >/tmp/surpress.out || cat /tmp/surpress.out
  /bin/rm /tmp/surpress.out
}

# parse and derive params
BUILD_DIR=$1
CACHE_DIR=$2
CUR_DIR=$(cd "$(dirname "$0")" && cd .. && pwd)
SIGIL_CACHE_FILE="${CACHE_DIR}/sigil-${SIGIL_VERSION}"

mkdir -p "$BUILD_DIR" "$CACHE_DIR"

if [[ ! -e "${BUILD_DIR}/www" ]]; then
  echo "-----> Copy static files to www"
  rm -rf "${CACHE_DIR}/www"
  mkdir -p "${CACHE_DIR}/www"

  # shellcheck disable=SC2086
  mv $BUILD_DIR/* "${CACHE_DIR}/www"
  mkdir -p "${BUILD_DIR}/www"

  # shellcheck disable=SC2086
  mv ${CACHE_DIR}/www/* "${BUILD_DIR}/www"
  # Check for a copy the nginx conf file override to the build dir
  [[ -f "${BUILD_DIR}/www/nginx.conf.erb" ]] && mv "${BUILD_DIR}/www/nginx.conf.erb" "${BUILD_DIR}"
  [[ -f "${BUILD_DIR}/www/nginx.conf.sigil" ]] && mv "${BUILD_DIR}/www/nginx.conf.sigil" "${BUILD_DIR}"
  [[ -f "${BUILD_DIR}/www/app-nginx.conf.sigil" ]] && mv "${BUILD_DIR}/www/app-nginx.conf.sigil" "${BUILD_DIR}"
  [[ -f "${BUILD_DIR}/www/mime.types" ]] && mv "${BUILD_DIR}/www/mime.types" "${BUILD_DIR}"
  [[ -f "${BUILD_DIR}/www/CHECKS" ]] && mv "${BUILD_DIR}/www/CHECKS" "${BUILD_DIR}"
  [[ -f "${BUILD_DIR}/www/app.json" ]] && mv "${BUILD_DIR}/www/app.json" "${BUILD_DIR}"
  rm -rf "${CACHE_DIR}/www"
fi

cd "$CACHE_DIR"

mkdir -p "$BUILD_DIR/sigil"

if [[ ! -f "$SIGIL_CACHE_FILE" ]]; then
  echo "-----> Download and cache sigil ${SIGIL_VERSION} via http"
  curl -fsSL "https://github.com/gliderlabs/sigil/releases/download/v${SIGIL_VERSION}/sigil-linux-amd64" -o "$SIGIL_CACHE_FILE"
  chmod +x "$SIGIL_CACHE_FILE"
fi

cp "$SIGIL_CACHE_FILE" "$BUILD_DIR/sigil/sigil-${SIGIL_VERSION}"
cp "$BUILD_DIR/sigil/sigil-${SIGIL_VERSION}" "$BUILD_DIR/sigil/sigil"
chmod +x "$BUILD_DIR/sigil/sigil"

if [[ ! -f "$BUILD_DIR/sigil/sigil" ]]; then
  echo " !     Missing sigil binary"
  exit 1
fi

# Invalidate cache if version doesn't match
if [[ -f "${CACHE_DIR}/bin/nginx" ]] && [[ ! -f "${CACHE_DIR}/bin/.nginx-version" ]]; then
  echo "-----> Cached nginx binary has no version marker, rebuilding"
  rm -rf "${CACHE_DIR:?}/bin"
elif [[ -f "${CACHE_DIR}/bin/nginx" ]] && [[ -f "${CACHE_DIR}/bin/.nginx-version" ]] && [[ "$(cat "${CACHE_DIR}/bin/.nginx-version")" != "$NGINX_VERSION" ]]; then
  CACHED_VERSION="$(cat "${CACHE_DIR}/bin/.nginx-version")"
  echo "-----> Cached nginx ${CACHED_VERSION} does not match required ${NGINX_VERSION}, rebuilding"
  rm -rf "${CACHE_DIR:?}/bin"
fi

if [[ -f "${CACHE_DIR}/bin/nginx" ]]; then
  echo "-----> Reusing nginx ${NGINX_VERSION} binary from cache"
  mkdir -p "$BUILD_DIR/nginx"
  # shellcheck disable=SC2086
  cp -r $CACHE_DIR/bin/* "$BUILD_DIR/nginx/"

elif curl -fsSL "https://github.com/${BUILDPACK_REPO}/releases/latest/download/nginx-${NGINX_VERSION}-linux-amd64" -o /tmp/nginx-linux-amd64 2>/dev/null; then
  echo "-----> Using precompiled nginx ${NGINX_VERSION} binary"
  mkdir -p "$BUILD_DIR/nginx" "${CACHE_DIR}/bin"
  chmod +x /tmp/nginx-linux-amd64
  cp /tmp/nginx-linux-amd64 "$BUILD_DIR/nginx/nginx"
  cp /tmp/nginx-linux-amd64 "${CACHE_DIR}/bin/nginx"
  echo "$NGINX_VERSION" >"${CACHE_DIR}/bin/.nginx-version"
  rm -f /tmp/nginx-linux-amd64

else
  if [[ ! -d "${NGINX_TARBALL%.tar.gz}" ]]; then
    echo "-----> Download and unzip nginx ${NGINX_VERSION} via http"
    curl -sSL "https://nginx.org/download/${NGINX_TARBALL}" -o "${NGINX_TARBALL}"
    tar xzf "${NGINX_TARBALL}" && rm -f "${NGINX_TARBALL}"
  fi

  if [[ ! -d "${PCRE_TARBALL%.tar.gz}" ]]; then
    echo "-----> Download and unzip pcre ${PCRE_VERSION} via http"
    curl -sSL "https://github.com/PCRE2Project/pcre2/releases/download/pcre2-${PCRE_VERSION}/${PCRE_TARBALL}" -o "${PCRE_TARBALL}"
    tar xzf "${PCRE_TARBALL}" && rm -f "${PCRE_TARBALL}"
  fi

  if [[ ! -d "${ZLIB_TARBALL%.tar.gz}" ]]; then
    echo "-----> Download and unzip zlib ${ZLIB_VERSION} via http"
    curl -sSL "https://github.com/madler/zlib/archive/v${ZLIB_VERSION}.tar.gz" -o "${ZLIB_TARBALL}"
    tar xzf "${ZLIB_TARBALL}" && rm -rf "${ZLIB_TARBALL}"
  fi

  cd "nginx-${NGINX_VERSION}"
  echo "-----> Compiling static nginx binary"
  mkdir "$BUILD_DIR/nginx"
  suppress ./configure \
    --prefix="$BUILD_DIR/nginx" \
    --with-pcre=../pcre2-${PCRE_VERSION} \
    --with-zlib=../zlib-${ZLIB_VERSION} \
    "${NGINX_CONFIGURE_FLAGS[@]}"

  sed -i "/CFLAGS/s/ \-O //g" objs/Makefile

  suppress make && suppress make install

  rm -rf "${CACHE_DIR:?}/bin" && mkdir -p "$CACHE_DIR/bin/"
  # shellcheck disable=SC2086
  cp -r $BUILD_DIR/nginx/* "$CACHE_DIR/bin/"
  echo "$NGINX_VERSION" >"${CACHE_DIR}/bin/.nginx-version"
fi

# Create logs directory for nginx's compiled-in default log paths
mkdir -p "$BUILD_DIR/nginx/logs"

# Update the PATH
mkdir -p "$BUILD_DIR/.profile.d"
cat >"$BUILD_DIR/.profile.d/nginx.sh" <<"EOF"
export PATH="$PATH:$HOME/nginx"
EOF

cd "$CUR_DIR"

# Add support for app-nginx.conf.sigil
if [ -f "$BUILD_DIR/app-nginx.conf.sigil" ]; then
  echo "-----> Using user provided app-nginx.conf.sigil"
  cp "$BUILD_DIR/app-nginx.conf.sigil" "$BUILD_DIR/nginx/app-nginx.conf.sigil"

# Allow deprecated nginx.conf.erb
elif [ -f "$BUILD_DIR/nginx.conf.erb" ]; then
  echo "-----> DEPRECATED: Using user provided nginx.conf.erb"
  cp "$BUILD_DIR/nginx.conf.erb" "$BUILD_DIR/nginx/nginx.conf.erb"

# ...else, force default file
else
  echo "-----> Using default app-nginx.conf.sigil"
  cp conf/app-nginx.conf.sigil "$BUILD_DIR/nginx/app-nginx.conf.sigil"
fi

# build mime.types unless overridden by user
if [ -f "$BUILD_DIR/mime.types" ]; then
  echo "-----> Using user provided mime.types"
  cp "$BUILD_DIR/mime.types" "$BUILD_DIR/nginx/mime.types"

else
  echo "-----> Using default mime.types"
  cp conf/mime.types "$BUILD_DIR/nginx/mime.types"
fi

# build a startup script
cat <<EOF >"$BUILD_DIR/start_nginx"
#!/usr/bin/env bash
rm -f /app/nginx/nginx.conf
if [[ -f /app/nginx/app-nginx.conf.sigil ]]; then
  /app/sigil/sigil -f /app/nginx/app-nginx.conf.sigil NGINX_ROOT="\$NGINX_ROOT" NGINX_DEFAULT_REQUEST="\$NGINX_DEFAULT_REQUEST" NGINX_WORKERS="\$NGINX_WORKERS" NGINX_WORKER_CONNECTIONS="\$NGINX_WORKER_CONNECTIONS" NGINX_CLIENT_BODY_TIMEOUT="\$NGINX_CLIENT_BODY_TIMEOUT" NGINX_CLIENT_MAX_BODY_SIZE="\$NGINX_CLIENT_MAX_BODY_SIZE" PORT="\$PORT" | cat -s > /app/nginx/nginx.conf
else
  erb /app/nginx/nginx.conf.erb > /app/nginx/nginx.conf
fi
exec /app/nginx/nginx -p /app/nginx -c /app/nginx/nginx.conf
EOF
chmod +x "$BUILD_DIR/start_nginx"
