#!/bin/bash

set -ex

#
# Generic Docker image pusher that follows the same push logic found in push_adamoracle
#
# Pushes smartcontract/<image>:circleci to relevant location based on passed args:
# push_image <branch> <gittag> <image>
# ie:
# push_image master 0.0.1 integration
# push_image develop echo_server
#
# Ignores anything not matching above.
# Key assumption: local version of smartcontract/<image>:circleci is the image
# to work with.
#
# Argument <image> is likely one of the following:
# test-integration
# test-cypress-job-server
# test-external-adapter
# test-echo-server
#

if [ -z "$DOCKERHUB_PASS" ]
then
  echo "Cannot push to dockerhub, credentials are missing."
  exit 1
fi

circle_branch="$1"
circle_tag="$2"
image_name="$3"

tag_and_push() {
  # ie: docker tag and push smartcontract/<image>:0.9.1, since DOCKER_TAG=0.9.1
  docker_tag=$1
  docker tag smartcontract/${image_name}:circleci smartcontract/${image_name}:${docker_tag}
  docker push smartcontract/${image_name}:${docker_tag}
}

branch_tag=`tools/ci/branch2tag ${circle_branch}` # ie: develop, latest, candidate-*, etc.
version_tag=`tools/ci/gittag2dockertag ${circle_tag}` # aka GIT_TAG. v0.9.1 -> 0.9.1

# version tag takes precedence.
if [ -n "${version_tag}" ]; then
  # Only if we don't have an explorer tag
  if [[ "${circle_tag}" =~ ^explorer-v([a-zA-Z0-9.]+) ]]; then
    echo "Skipping publishing for this branch/tag."
  else
    tag_and_push "$version_tag"
    # if version tag, also push latest.
    # ie: after pushing smartcontract/<image>:0.0.1, also update smartcontract/<image>:latest
    tag_and_push latest
  fi
elif [ -n "$branch_tag" ]; then
  # Only if we're not on explorer branch
  if [[ "${circle_branch}" =~ ^release(s)?\/explorer-(.+)$ ]]; then
    echo "Skipping publishing for this branch/tag."
  else
    tag_and_push "$branch_tag"
  fi
else
  echo "Skipping publishing for this branch/tag."
fi
