#!/bin/bash

# remove trailing slash if exists
DOCKER_REPO=${DOCKER_REPO%/}

echo "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
date
echo building image \"$IMAGE_NAME\" in repository \"$DOCKER_REPO\" using dockerfile \"$DOCKERFILE_PATH\"
echo image was triggered by automated build for tag \"$DOCKER_TAG\"
echo " based on branch \"$SOURCE_BRANCH\"  and commit \"$SOURCE_COMMIT\""
echo " commit message was \"$COMMIT_MSG\""
echo && echo && echo
echo "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"

# verify that version.sbt and tag match for non-snapshot (ENV variable DOCKER_VERIFY_TAG must be set to 1)
if [ $DOCKER_VERIFY_TAG -eq 1 ] && [[ "$DOCKER_TAG" != *"-SNAPSHOT" ]]; then
  echo validating version number...
  TMP_VERSION=$(cat ../version.sbt)
  TMP_VERSION=${TMP_VERSION:25:99}
  VERSION=${TMP_VERSION%\"}
  if [ "$DOCKER_TAG" != "base-v$VERSION" ]; then
    echo "version number mismatch (Docker/Tag: $DOCKER_TAG, Project: $VERSION), aborting!"
    exit 1
  fi
fi


./dev-build-images.sh "$DOCKER_REPO"
status=$?

if [[ $status -eq 0 ]]; then
  echo "#### pushing images ####"
  ./dev-push-images.sh "$DOCKER_REPO"
fi


echo && echo && date
echo "|||||||||||||||||||||||||||||||||||||||||||||  done  |||||||||||||||||||||||||||||||||||||||||||||"


###################################
# available variables
## SOURCE_BRANCH: the name of the branch or the tag that is currently being tested.
## SOURCE_COMMIT: the SHA1 hash of the commit being tested.
## COMMIT_MSG: the message from the commit being tested and built.
## DOCKER_REPO: the name of the Docker repository being built.
## DOCKERFILE_PATH: the dockerfile currently being built.
## DOCKER_TAG: the Docker repository tag being built.
## IMAGE_NAME: the name and tag of the Docker repository being built. (This variable is a combination of DOCKER_REPO:DOCKER_TAG.)
###################################