#!/bin/bash

set -e

. bin/build_utils

readonly VERSION="$(short_version_tag)"
readonly FULL_VERSION_TAG="$(full_version_tag)"
readonly REDHAT_IMAGE="scan.connect.redhat.com/ospid-56594c20-22fc-4eeb-9c2e-402cf43bcb79/secrets-provider-for-k8s"

readonly TAGS=(
  "$VERSION"
  "latest"
)

readonly IMAGE_NAME="secrets-provider-for-k8s"

readonly REGISTRY='cyberark'

# if the tag matches the VERSION, push VERSION and latest releases
# and x and x.y releases
if [ "$GIT_DESCRIPTION" = "v${VERSION}" ]; then
  echo "Revision $GIT_DESCRIPTION matches version $VERSION exactly. Pushing to Dockerhub..."

  for tag in "${TAGS[@]}" $(gen_versions "$VERSION"); do
    echo "Tagging and pushing $REGISTRY/$IMAGE_NAME:$tag"

    docker tag "$IMAGE_NAME:$FULL_VERSION_TAG" "$REGISTRY/$IMAGE_NAME:$tag"
    docker push "$REGISTRY/$IMAGE_NAME:$tag"
  done

  # Publish only latest to Redhat Registries
  echo "Tagging and pushing ${REDHAT_IMAGE}"
  docker tag "secrets-provider-for-k8s-redhat:${FULL_VERSION_TAG}" "${REDHAT_IMAGE}:${VERSION}"

  if docker login scan.connect.redhat.com -u unused -p "${REDHAT_API_KEY}"; then
    # you can't push the same tag twice to redhat registry, so ignore errors
    if ! docker push "${REDHAT_IMAGE}:${VERSION}"; then
      echo 'Red Hat push FAILED! (maybe the image was pushed already?)'
      exit 0
    fi
  else
    echo 'Failed to log in to scan.connect.redhat.com'
    exit 1
  fi
elif [ "$BRANCH_NAME" = "main" ]; then
  echo "Successful Master build. Tagging and pushing $REGISTRY/$IMAGE_NAME:edge"
  docker tag "$IMAGE_NAME:$FULL_VERSION_TAG" "$REGISTRY/$IMAGE_NAME:edge"
  docker push "$REGISTRY/$IMAGE_NAME:edge"
fi
