#!/usr/bin/env bash

set -euo pipefail
set -x

project_name=${ZOOX_PROJECT_NAME}

cd ../..

./scripts/setup/setup.sh dev --tags bazel
source scripts/shell/zooxrc.sh

cd "$(bazel_root)/pipedream/slurm/pyslurm_src"

python3.6 setup.py build --slurm-inc=/usr/local/include --slurm-lib=/usr/local/lib && \
python3.6 setup.py install

cd "$(bazel_root)/pipedream/slurm"

bazel build --announce_rc --local_default_allow_network --config pipedream --verbose_failures //pipedream/slurm:pipedream_slurm

./dockerize.sh

#if a tag with the project name
git_sha=$(git rev-parse HEAD)
git_tag=$(git tag --points-at "${git_sha}")
should_push_new_docker_tag="false"
if [[ "${git_tag}" =~ "${project_name}__" ]]; then
  should_push_new_docker_tag="true"
fi
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")

build_number=$(date +%s)

# If the git sha has tags associated with it then publish the version as released (empty qualifier) and also add skip
# flags to avoid build failures due to publish errors during repeated builds in CI (as the released package may already
# exist from a previous build). If the branch is master and has no tags then mark the package as dev build otherwise
# it must be a non master branch so mark the build with branch name.
if [[ $should_push_new_docker_tag == "true" ]]; then
    qualifier=""
    docker_qualifier=""
elif [[ "${current_git_branch}" == "master" ]]; then
    qualifier=".dev${build_number}"
    docker_qualifier="-dev"
else
    qualifier=".${current_git_branch}${build_number}"
    docker_qualifier="-${current_git_branch}"
fi

# Get the unqualified version and set the docker variables.
# Run this to make sure that test eggs are created and don't interfere with commands.
python setup.py --help
setup_version=$(python setup.py --version)

docker_sock=${DOCKER_SOCK:-''}

# Automatically set docker sock to default path if DOCKER_SOCK is not provided and default docker sock exists
if [[ -z "${docker_sock}" && -e "/var/run/docker.sock" ]]; then
    docker_sock="unix:///var/run/docker.sock"
else
    docker_sock=${DOCKER_SOCK:-"unix:///var/run/ci_docker.sock"}
fi

image_version="${setup_version}${docker_qualifier}"
docker --host "${docker_sock}" tag docker-registry.zooxlabs.com/${project_name}:latest docker-registry.zooxlabs.com/${project_name}:${image_version}

