#!/usr/bin/env bash

set -euo pipefail

bright_red='\u001b[31;1m'
bright_green='\u001b[32;1m'
reset_color='\033[0m'

# Uncommited changes are not allowed.
if [[ -n $(git status -s) ]]
then
  echo -e "${bright_red}Please stash uncommited changes. ${reset_color}"
  exit 1;
fi

current_directory="$(pwd)"


cleanup() {
    # restore the working directory
    cd ${current_directory}
}

trap cleanup EXIT

exit_code=0
function tag_project() {
    project="${1}"
    version_number="$(python setup.py --version)"
    tag="${project}__${version_number}"
    # Prevent overwriting build versions.
    if [[ -n $(git ls-remote origin refs/tags/${tag}) ]]
    then
        echo -e "${bright_red}Tag exists on remote\t${tag}${reset_color}"
        exit_code=1;
        return 0;
    fi

    git tag ${tag}
    git push origin ${tag} --quiet
    echo -e "${bright_green}Successfully tagged\t${tag}${reset_color}"
}

function filter_container_id() {
    tail -1 | awk '{ print $3 }'
}

cd ${ZOOX_WORKSPACE_ROOT}/web_apps/hwsd/hwsd_component
tag_project hwsd_component-2

cd ${ZOOX_WORKSPACE_ROOT}/web_apps/hwsd/hwsd_gateway
tag_project hwsd_gateway-2

cd ${ZOOX_WORKSPACE_ROOT}/web_apps/hwsd/hwsd_run
tag_project hwsd_run-2

cd ${ZOOX_WORKSPACE_ROOT}/web_apps/hwsd/hwsd_station
tag_project hwsd_station-2

cd ${ZOOX_WORKSPACE_ROOT}/web_apps/hwsd/hwsd_test
tag_project hwsd_test-2

cd ${current_directory}
exit ${exit_code}
