#!/bin/bash
# Copyright 2023 The gRPC Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Generates dockerimage_current_versions.bzl file from the .current_version
# files found throughout the repository.

set -e

cd $(dirname $0)/../..

OUTPUT_FILE=tools/bazelify_tests/dockerimage_current_versions.bzl
if [ "${CHECK_MODE}" != "" ]
then
  # generate into temporary file instead
  ORIG_FILE="${OUTPUT_FILE}"
  OUTPUT_FILE="$(mktemp)"
fi

# Generate license header and module docstring.
cat >"${OUTPUT_FILE}" << EOF
# Copyright 2023 The gRPC Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
This file is generated by generate_dockerimage_current_versions_bzl.sh
It makes the info from testing docker image *.current_version files
accessible to bazel builds.
"""

EOF

echo "DOCKERIMAGE_CURRENT_VERSIONS = {" >>"${OUTPUT_FILE}"

for current_version_file in $(find tools/ third_party/rake-compiler-dock -name '*.current_version' | LC_ALL=C sort)
do
  # Remove the docker image tag and only keep the SHA256 digest for the dockerimage.
  # For some reason, bazel's "container-image" exec property doesn't accept image spec
  # with both tag and SHA256 digest.
  echo "    \"${current_version_file}\": \"docker://$(cat ${current_version_file} | sed 's/:[a-f0-9]*@sha256/@sha256/')\"," >>"${OUTPUT_FILE}"
done

echo "}" >>"${OUTPUT_FILE}"

if [ "${CHECK_MODE}" != "" ]
then
  echo "Checking that ${ORIG_FILE} is up-to-date."
  diff "${OUTPUT_FILE}" "${ORIG_FILE}" || CHECK_FAILED=true

  if [ "${CHECK_FAILED}" != "" ]
  then
    echo "CHECK FAILED: Generated file ${ORIG_FILE} is out of date and needs to be regenerated."
    exit 1
  else
    echo "${ORIG_FILE} is up-to-date."
  fi
else
  echo "Generated ${OUTPUT_FILE}"
fi