#!/usr/bin/env bash
set -euo pipefail

docker_registry_url=${DOCKER_REGISTRY_URL:-"docker-registry.zooxlabs.com/"}
docker_sock=${DOCKER_SOCK:-"unix:///var/run/ci_docker.sock"}
docker_command="sudo docker --host ${docker_sock}"

project_name='python_service_docker_image'
version=1.0.0
qualifier=''

git_sha=$(git rev-parse HEAD)
current_git_branch=${ZOOX_BRANCH_NAME:-""}

if [[ -z "${current_git_branch}" ]]; then
    current_git_branch=$(git rev-parse --abbrev-ref HEAD)
fi

current_git_branch=$(echo "${current_git_branch}" | sed "s|/|_|g" | sed "s|--*|-|g")

git_tag=$(git tag --points-at "${git_sha}")

# If the git sha has tags associated with it then publish version as released (empty qualifier).
# If the branch is master and has no tags then mark the image as dev.
# Otherwise it must be a branch so mark the image with branch name.
if [[ "${git_tag}" == "${project_name}_" ]]; then
    qualifier=""
elif [[ "${current_git_branch}" == "master" ]]; then
    qualifier="-dev"
else
    qualifier="-${current_git_branch}"
fi

image_version="${version}${qualifier}"
image_name="${docker_registry_url}${project_name}:${image_version}"
latest_image_name="${docker_registry_url}${project_name}:latest"

# Create the docker image and push it if the branch is not HEAD or qualifier is empty. Also, push it as latest if the
# current branch is master.
if [[ "${current_git_branch}" != "HEAD" || -z "${qualifier}" ]]; then
    ${docker_command} build --tag "${image_name}" .
    ${docker_command} push "${image_name}"

    if [[ "${current_git_branch}" == "master" ]]; then
        ${docker_command} tag "${image_name}" "${latest_image_name}"
        ${docker_command} push "${latest_image_name}"
    fi
fi
