#!/usr/bin/env bash

# The regular ./build_and_push_ingest_job.sh script in data/ingest/docker_images
# doesn't work for us because it expect to run the ingest command with "-h" to
# verify that it works, except gflags doesn't populate that option. It only uses
# "--help", but we can't use that either, because gflags will exit with exit
# code 1 when you use --help and the build_and_push script interprets that exit
# code as "your job is broken, so I'm not going to push it to Artifactory."
#
# So here we are. *sigh*
#
# At least we can infer all the arguments for you so that's neat... I guess.

set -exuo pipefail

cd "$( (builtin cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) )"

image="perf_data_image"
target="${image}"
environ="prod"
current_version=$(${ZOOX_WORKSPACE_ROOT}/data/ingest/docker_images/get_latest_tag.py ${image})
next_version=$(expr ${current_version} + 1)

# Docker tag fragments
root_path="data/ingest/docker_images"
dest_path="ingest.docker.zooxlabs.com/${root_path}"


# Pull base images
../../../data/ingest/docker_images/ingest_pipeline_base/pull.sh
../../../data/ingest/docker_images/ingest_pipeline_py3_base/pull.sh

# Build the ingest docker image.
bazel run "//${root_path}:${image}" -- --norun

# Customize the image by installing the on-vehicle kernel's linux-tools.
docker build -t "bazel/${root_path}:${image}" - < Dockerfile

# Tag the image with version and environment
docker tag "bazel/${root_path}:${image}" "${dest_path}/${target}:${next_version}"
docker push "${dest_path}/${target}:${next_version}"

docker tag "${dest_path}/${target}:${next_version}" "${dest_path}/${target}:${environ}"
docker push "${dest_path}/${target}:${environ}"

echo "Done!"
