#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_AVAILABLE_PATH/scheduler-docker-local/internal-functions"

trigger-scheduler-docker-local-scheduler-register-retired() {
  declare desc="register a container for retiring"
  declare trigger="scheduler-register-retired"
  declare APP="$1" CONTAINER_ID="$2" WAIT="${3:-60}"
  local IMAGE_ID

  if [[ -z "$CONTAINER_ID" ]]; then
    return
  fi

  if [[ "$DOKKU_SKIP_IMAGE_RETIRE" != "true" ]]; then
    IMAGE_ID="$("$DOCKER_BIN" container inspect "$CONTAINER_ID" --format "{{.Image}}" 2>/dev/null | cut -d: -f2 || true)"
  fi
  fn-scheduler-docker-local-register-retired "container" "$APP" "$CONTAINER_ID" "$WAIT"

  if [[ -n "$IMAGE_ID" ]] && [[ -z "$DOKKU_SKIP_IMAGE_CLEANUP_REGISTRATION" ]]; then
    ALT_IMAGE_TAGS="$("$DOCKER_BIN" image inspect --format '{{ index .Config.Labels "com.dokku.docker-image-labeler/alternate-tags" }}' "$IMAGE_ID" 2>/dev/null || true)"

    fn-scheduler-docker-local-register-retired "image" "$APP" "$IMAGE_ID" "$WAIT"
    if [[ -n "$ALT_IMAGE_TAGS" ]]; then
      ALT_IMAGE_TAG="$(echo "$ALT_IMAGE_TAGS" | jq -r ".[]")"
      if [[ "$(plugn trigger git-get-property "$APP" "source-image")" != "$ALT_IMAGE_TAG" ]]; then
        ALT_IMAGE_ID="$("$DOCKER_BIN" image inspect --format '{{ .Id }}' "$ALT_IMAGE_TAG" 2>/dev/null || true)"
        fn-scheduler-docker-local-register-retired "image" "$APP" "$(echo "$ALT_IMAGE_ID" | cut -d ':' -f2)" "$WAIT"
      fi
    fi
  fi
}

trigger-scheduler-docker-local-scheduler-register-retired "$@"
