#!/usr/bin/env bash
#
# Build the ingest_pipeline_base image with a specific version
# Then tag it with an environment
#
# Example: ./build_and_push_image.sh prod 17

set -xeuo pipefail

if [[ -z "${1:-}" || "$1" == '--help' || "$1" == '-h' ]]; then
  echo "Usage: $0 ENVIRONMENT VERSION"
  exit 1
fi

if [[ ! -v ZOOX_WORKSPACE_ROOT ]]; then
  echo "$0 must be run from within a ZOOX_WORKSPACE context"
  echo "   ZOOX_WORKSPACE_ROOT environment variable not set"
  exit 1
fi

environ="$1"
version="$2"
image_name_version="zrnwv.docker.zooxlabs.com/backend_base:$version"
image_name_environ="zrnwv.docker.zooxlabs.com/backend_base:$environ"

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

# Create local copies of files that this image needs
ln --force ../../../../scripts/ansible/roles/apt_sources/templates/trusty-sources.list
ln --force ../../../../scripts/ansible/roles/apt_sources/files/llvm-snapshot.gpg.key llvm-snapshot.gpg.key
ln --force ../../../../scripts/ansible/roles/apt_sources/files/ubuntu-toolchain-r-test.asc
ln --force ../../../../scripts/setup/get-pip.py
ln --force ../../../../scripts/ansible/roles/python_pip/files/pip.conf

# Not on this filesystem, so do a copy
cp /mnt/flashblade/prebuilt_binaries/ingest/.ingest_aws_credentials ./credentials
# And make sure that they're deleted after
function cleanup {
  /bin/rm --force llvm-snapshot.gpg.key trusty-sources.list ubuntu-toolchain-r-test.asc credentials get-pip.py pip.conf
}
trap cleanup EXIT

(
  docker build ./ --tag "$image_name_version"
  docker push "$image_name_version"
  docker build ./ --tag "$image_name_environ"
  docker push "$image_name_environ"
  docker save "$image_name_environ" --output /tmp/zrn_zrnwv_backend_base.tgz
  ${ZOOX_WORKSPACE_ROOT}/scripts/build/upload-to-third-party.sh /tmp/zrn_zrnwv_backend_base.tgz
)

echo "Making shallow image"
${ZOOX_WORKSPACE_ROOT}/docker_images/bazel_package/create.sh zrnwv.docker.zooxlabs.com backend_base $version ../backend_base_image

echo Success!
echo
echo "NOTE: You have just successfully uploaded an image to zrnwv.docker.zooxlabs.com"
echo "      To use this image run "
echo "      ./docker_images/bazel_package/create.sh zrnwv.docker.zooxlabs.com backend_base tag ../backend_base_image"
