#!/usr/bin/env bash
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_AVAILABLE_PATH/config/functions"
source "$PLUGIN_AVAILABLE_PATH/builder-dockerfile/internal-functions"
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x

trigger-builder-dockerfile-builder-build() {
  declare desc="builder-dockerfile builder-build plugin trigger"
  declare trigger="builder-build"
  declare BUILDER_TYPE="$1" APP="$2" SOURCECODE_WORK_DIR="$3"

  if [[ "$BUILDER_TYPE" != "dockerfile" ]]; then
    return
  fi

  dokku_log_info1 "Building $APP from Dockerfile"

  local IMAGE=$(get_app_image_name "$APP")
  local DOKKU_DOCKERFILE_CACHE_BUILD=$(config_get "$APP" "DOKKU_DOCKERFILE_CACHE_BUILD")
  local DOKKU_DOCKER_BUILD_OPTS=$(config_get "$APP" "DOKKU_DOCKER_BUILD_OPTS")
  local DOCKER_BUILD_LABEL_ARGS=("--label=dokku" "--label=org.label-schema.schema-version=1.0" "--label=org.label-schema.vendor=dokku" "--label=com.dokku.image-stage=build" "--label=com.dokku.builder-type=dockerfile" "--label=com.dokku.app-name=$APP")

  pushd "$SOURCECODE_WORK_DIR" &>/dev/null

  plugn trigger pre-build-dockerfile "$APP"

  [[ "$DOKKU_DOCKERFILE_CACHE_BUILD" == "false" ]] && DOKKU_DOCKER_BUILD_OPTS="$DOKKU_DOCKER_BUILD_OPTS --no-cache"
  local DOCKER_ARGS=$(: | plugn trigger docker-args-build "$APP" "$BUILDER_TYPE")
  DOCKER_ARGS+=$(: | plugn trigger docker-args-process-build "$APP" "$BUILDER_TYPE")

  # strip --link, --volume and -v args from DOCKER_ARGS
  local DOCKER_ARGS=$(sed -e "s/^--link=[[:graph:]]\+[[:blank:]]\?//g" -e "s/^--link[[:blank:]]\?[[:graph:]]\+[[:blank:]]\?//g" -e "s/^--volume=[[:graph:]]\+[[:blank:]]\?//g" -e "s/^--volume[[:blank:]]\?[[:graph:]]\+[[:blank:]]\?//g" -e "s/^-v[[:blank:]]\?[[:graph:]]\+[[:blank:]]\?//g" <<<"$DOCKER_ARGS")
  declare -a ARG_ARRAY
  eval "ARG_ARRAY=($DOCKER_ARGS)"

  eval "$(config_export app "$APP")"
  "$DOCKER_BIN" image build "${DOCKER_BUILD_LABEL_ARGS[@]}" $DOKKU_GLOBAL_BUILD_ARGS "${ARG_ARRAY[@]}" ${DOKKU_DOCKER_BUILD_OPTS} -t $IMAGE .

  plugn trigger ports-set-detected "$APP" "$(fn-builder-dockerfile-get-detect-port-map "$APP" "$IMAGE" "$SOURCECODE_WORK_DIR/Dockerfile")"
  plugn trigger post-build-dockerfile "$APP"
}

trigger-builder-dockerfile-builder-build "$@"
