#!/bin/sh -e
# Build the backend base image.
# Requires CI_PROJECT_DIR and CI_REGISTRY_IMAGE as well as either VERSION or CI_COMMIT_TAG.
# If VERSION is not set, CI_COMMIT_TAG must start with "base-" and will be used as "base-$VERSION".
# If CI_REGISTRY is set, will push the image to the specified registry.
# If CI_REGISTRY, CI_REGISTRY_USER and CI_REGISTRY_PASSWORD are set, will run `docker login` before pushing.

if [ -z "$VERSION" ]; then
	# Ensure this is a base tag, then tell sh to remove the base- prefix.
	case $CI_COMMIT_TAG in
		base-*)
			VERSION=${CI_COMMIT_TAG#base-};;
		*)
			echo build-base can only be used with 'base-*' tags.
			exit 1;;
	esac
fi

if [ -z "$VERSION" -o -z "$CI_PROJECT_DIR" -o -z "$CI_REGISTRY_IMAGE" ]; then
	echo Missing environment variables
	exit 1
fi

if [ -n "$CI_REGISTRY" -a -n "$CI_REGISTRY_USER" -a -n "$CI_REGISTRY_PASSWORD" ]; then
	echo Logging in to container registry…
	echo $CI_REGISTRY_PASSWORD | docker login -u $CI_REGISTRY_USER --password-stdin $CI_REGISTRY
fi

IMAGE_TAG="$CI_REGISTRY_IMAGE/base:$VERSION"
IMAGE_LATEST="$CI_REGISTRY_IMAGE/base:latest"
docker build --no-cache "$CI_PROJECT_DIR/base" -t "$IMAGE_TAG" -t "$IMAGE_LATEST"
docker push "$IMAGE_TAG"
docker push "$IMAGE_LATEST"
