#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_AVAILABLE_PATH/nginx-vhosts/functions"

trigger-nginx-vhosts-docker-args-process-deploy() {
  declare desc="nginx-vhosts docker-args-process-deploy plugin trigger"
  declare trigger="docker-args-process-deploy"
  declare APP="$1" IMAGE_SOURCE_TYPE="$2" IMAGE_TAG="$3" PROC_TYPE="$4" CONTAINER_INDEX="$5"
  local output
  local STDIN=$(cat)

  if [[ "$PROC_TYPE" != "web" ]]; then
    return
  fi

  if [[ "$(plugn trigger proxy-type "$APP")" != "nginx" ]]; then
    return
  fi

  if [[ "$(plugn trigger proxy-is-enabled "$APP")" != "true" ]]; then
    return
  fi

  if ! plugn trigger domains-vhost-enabled "$APP" 2>/dev/null; then
    return
  fi

  # ensure we have a port mapping
  plugn trigger ports-configure "$APP"

  output="$output '--label=nginx.access-log-format=$(fn-nginx-access-log-format "$APP")'"
  output="$output '--label=nginx.bind-address-ipv4=$(fn-nginx-bind-address-ipv4 "$APP")'"
  output="$output '--label=nginx.bind-address-ipv6=$(fn-nginx-bind-address-ipv6 "$APP")'"
  output="$output '--label=nginx.client-max-body-size=$(fn-nginx-client-max-body-size "$APP")'"
  output="$output '--label=nginx.hsts-include-subdomains=$(fn-nginx-hsts-include-subdomains "$APP")'"
  output="$output '--label=nginx.hsts-max-age=$(fn-nginx-hsts-max-age "$APP")'"
  output="$output '--label=nginx.hsts-preload=$(fn-nginx-hsts-preload "$APP")'"
  output="$output '--label=nginx.hsts=$(fn-nginx-hsts-is-enabled "$APP")'"
  output="$output '--label=nginx.https-port=443'"
  output="$output '--label=nginx.domains=$(plugn trigger domains-list "$APP" | xargs)'"
  output="$output '--label=nginx.initial-network=$(plugn trigger network-get-property "$APP" initial-network)'"
  output="$output '--label=nginx.port-mapping=$(plugn trigger ports-get "$APP" | xargs)'"
  output="$output '--label=nginx.proxy-buffer-size=$(fn-nginx-proxy-buffer-size "$APP")'"
  output="$output '--label=nginx.proxy-buffering=$(fn-nginx-proxy-buffering "$APP")'"
  output="$output '--label=nginx.proxy-buffers=$(fn-nginx-proxy-buffers "$APP")'"
  output="$output '--label=nginx.proxy-busy-buffer-size=$(fn-nginx-proxy-busy-buffers-size "$APP")'"
  output="$output '--label=nginx.proxy-read-timeout=$(fn-nginx-proxy-read-timeout "$APP")'"
  output="$output '--label=nginx.x-forwarded-for-value=$(fn-nginx-x-forwarded-for-value "$APP")'"
  output="$output '--label=nginx.x-forwarded-port-value=$(fn-nginx-x-forwarded-port-value "$APP")'"
  output="$output '--label=nginx.x-forwarded-proto-value=$(fn-nginx-x-forwarded-proto-value "$APP")'"
  output="$output '--label=nginx.x-forwarded-ssl=$(fn-nginx-x-forwarded-ssl "$APP")'"

  echo -n "$STDIN$output"
}

trigger-nginx-vhosts-docker-args-process-deploy "$@"
