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

dokku_release_cmd() {
  declare desc="release phase"
  local cmd="release"
  local APP="$2"; local IMAGE_SOURCE_TYPE="$3"; local IMAGE_TAG="$4"; local IMAGE=$(get_app_image_name "$APP" "$IMAGE_TAG")
  verify_app_name "$APP"

  case "$IMAGE_SOURCE_TYPE" in
    herokuish)
      plugn trigger pre-release-buildpack "$APP" "$IMAGE_TAG"
      if [[ -n $(config_export global) ]]; then
        local id=$(config_export global | docker run "$DOKKU_GLOBAL_RUN_ARGS" -i -a stdin "$IMAGE" /bin/bash -c "mkdir -p /app/.profile.d && cat > /app/.profile.d/00-global-env.sh")
        test "$(docker wait "$id")" -eq 0
        docker commit "$id" "$IMAGE" > /dev/null
      fi
      if [[ -n $(config_export app "$APP") ]]; then
        local id=$(config_export app "$APP" | docker run "$DOKKU_GLOBAL_RUN_ARGS" -i -a stdin "$IMAGE" /bin/bash -c "mkdir -p /app/.profile.d && cat > /app/.profile.d/01-app-env.sh")
        test "$(docker wait "$id")" -eq 0
        docker commit "$id" "$IMAGE" > /dev/null
      fi
      plugn trigger post-release-buildpack "$APP" "$IMAGE_TAG"
      ;;

    dockerfile)
      # buildstep plugins don't necessarily make sense for dockerfiles. call the new breed!!!
      plugn trigger pre-release-dockerfile "$APP" "$IMAGE_TAG"
      plugn trigger post-release-dockerfile "$APP" "$IMAGE_TAG"
      ;;

    *)
      dokku_log_fail "Releasing image source type $IMAGE_SOURCE_TYPE not supported!"
      ;;
  esac
}

dokku_release_cmd "$@"
