#!/usr/bin/env bash

set -euo pipefail

docker_registry_url=${DOCKER_REGISTRY_URL:-"docker-registry.zooxlabs.com/"}
docker_image_name="angular-hwsd-test"
docker_sock=${DOCKER_SOCK:-''}
docker_qualifier=""

# Automatically set docker sock to default path if DOCKER_SOCK is not is 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

docker_command="sudo docker --host ${docker_sock}"

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 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 [[ "${git_tag}" =~ "angular-hwsd-test__" ]]; then
    docker_qualifier=""
elif [[ "${current_git_branch}" == "master" ]]; then
    docker_qualifier="-dev"
else
    docker_qualifier="-${current_git_branch}"
fi

./install_node.sh

sudo npm install -g @angular/cli@8.0.3

# Install dependencies.
npm install

# Lint the entire project.
ng lint

# Run unit tests.
# ng test

# Make a production build.
ng build

# Get the package full name.
project_version=$(node --print "require('./package.json').version")
image_version="${project_version}${docker_qualifier}"
image_name="${docker_registry_url}${docker_image_name}:${image_version}"
latest_image_name="${docker_registry_url}${docker_image_name}:latest"

# Create the docker image and push it if the branch is not HEAD or qualifier is empty. Also, push it as `latest` tag if
# the current branch is master.
if [[ "${current_git_branch}" != "HEAD" || -z "${docker_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
