#!/bin/bash

set -ex

#
# Pushes smartcontract/adamoracle:circleci to relevant location based on passed args:
# push_adamoracle <branch> <gittag>
# ie:
# push_adamoracle master 0.0.1
# push_adamoracle develop
# push_adamoracle release/0.0.1
#
# Ignores anything not matching above.
# Key assumption: local version of smartcontract/adamoracle:circleci is the image
# to work with.
#

# Our registry, hosted on Public ECR.
AWS_ECR_URL=public.ecr.aws/z0b1w9r9

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

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

PROJECT_ROOT=$(git rev-parse --show-toplevel)
pushd $PROJECT_ROOT >/dev/null

tag_and_push() {
  # ie: docker tag and push smartcontract/adamoracle:0.9.1, since DOCKER_TAG=0.9.1
  export DOCKER_TAG=$1
  (
    set -x
    docker tag smartcontract/adamoracle:circleci smartcontract/adamoracle:${DOCKER_TAG}
    docker tag smartcontract/adamoracle:circleci-nonroot "smartcontract/adamoracle:${DOCKER_TAG}-nonroot"
  )
  (
    set -x
    docker tag smartcontract/adamoracle:circleci "${AWS_ECR_URL}/adamoracle:${DOCKER_TAG}"
    docker tag smartcontract/adamoracle:circleci-nonroot "${AWS_ECR_URL}/adamoracle:${DOCKER_TAG}-nonroot"
  )
  make dockerpush
}

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/adamoracle:0.0.1, also update smartcontract/adamoracle:latest
    tag_and_push "latest.$circle_sha1"
  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.$circle_sha1"
  fi
else
  echo "Skipping publishing for this branch/tag."
fi
