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

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

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

  local stack="$(plugn trigger buildpack-stack-name "$APP")"
  if [[ -n "$stack" ]]; then
    DOKKU_CNB_BUILDER="$stack"
  fi

  dokku_log_info1 "Building $APP from cnb stack $DOKKU_CNB_BUILDER (experimental)..."

  if ! command -v "pack" &>/dev/null; then
    dokku_log_fail "Missing pack, install it"
  fi

  local IMAGE=$(get_app_image_name "$APP")

  pushd "$SOURCECODE_WORK_DIR" &>/dev/null

  ENV_ARGS=($(config_export app "$APP" --format pack-keys --merged))
  eval "$(config_export app "$APP" --merged)"

  if fn-plugn-trigger-exists "pre-build-pack"; then
    dokku_log_warn "Deprecated: please upgrade plugin to use 'pre-build' plugin trigger instead of pre-build-pack"
    plugn trigger pre-build-pack "$APP" "$SOURCECODE_WORK_DIR"
  fi
  plugn trigger pre-build "$BUILDER_TYPE" "$APP" "$SOURCECODE_WORK_DIR"

  local DOCKER_ARGS=$(: | plugn trigger docker-args-build "$APP" "$BUILDER_TYPE")
  [[ "$DOKKU_TRACE" ]] && DOCKER_ARGS+=" --env=TRACE=true "
  DOCKER_ARGS+=$(: | plugn trigger docker-args-process-build "$APP" "$BUILDER_TYPE")

  DOCKER_ARGS=" $DOCKER_ARGS "
  declare -a ARG_ARRAY
  eval "ARG_ARRAY=($DOCKER_ARGS)"

  eval set -- "$DOCKER_ARGS"

  declare -a PACK_ARGS
  while true; do
    case "$1" in
      --volume=* | -v=*)
        PACK_ARGS+=("$1")
        shift
        ;;
      --volume | -v)
        PACK_ARGS+=("--volume")
        PACK_ARGS+=("$2")
        shift 2
        ;;
      *)
        break
        ;;
    esac
  done

  pack build "$IMAGE" --builder "$DOKKU_CNB_BUILDER" --path "$SOURCECODE_WORK_DIR" --default-process web "${PACK_ARGS[@]}" "${ENV_ARGS[@]}"
  docker-image-labeler relabel --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=pack --label=com.dokku.app-name=$APP "$IMAGE"

  # ensure we have a port mapping
  plugn trigger ports-configure "$APP"
  plugn trigger ports-set-detected "$APP" "http:$(plugn trigger ports-get-property "$APP" proxy-port):5000"

  if fn-plugn-trigger-exists "post-build-pack"; then
    dokku_log_warn "Deprecated: please upgrade plugin to use 'post-build' plugin trigger instead of post-build-pack"
    plugn trigger post-build-pack "$APP" "$SOURCECODE_WORK_DIR"
  fi
  plugn trigger post-build "$BUILDER_TYPE" "$APP" "$SOURCECODE_WORK_DIR"
}

trigger-builder-pack-builder-build "$@"
