#!/bin/sh

# Copyright 2021-2022, 2024, 2026 Google LLC
#
# 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
#
#     https://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.

# Run this script to regenerate the Bazel output and coverage file in
# coverage.org.

set -eu

org="$(bazel --quiet info workspace)/testdata/coverage.org" || exit
dir="$(mktemp -d)" || exit

# Set up a basic repository layout in the temporary directory.
cp -- "${org:?}" "${dir:?}/.tangle.org" || exit
emacs --quick --batch --visit="${dir:?}/.tangle.org" \
  --funcall='org-babel-tangle' || exit

# Remove tangled “bazel-out” directory containing the previous coverage data.
# This would interfere with the Bazel run below.
rm -r -- "${dir:?}/bazel-out"

testlogs="$(cd "${dir:?}" && bazel --nohome_rc --quiet info bazel-testlogs)"

# Generate fake tangled files with links so we can use ‘org-babel-detangle’.
(
  set -eu
  echo '# [[file:detangle.org::bazel.out][bazel.out]]'
  # We explicitly compile with the current directory set to a subdirectory to
  # ensure that repository-relative filenames still work as expected.
  cd "${dir:?}/src" || exit
  bazel --nohome_rc --quiet coverage --attempt_to_print_relative_paths //... 2>&1
  echo '# bazel.out ends here'
) > "${dir:?}/bazel.out.tmp" || exit

# Parse output to find location of coverage.dat.  The output should be
# relatively stable, cf. https://bazel.build/run/scripts#parsing-output.
dat="$(sed -E -n -e 's|^  (/.+/coverage\.dat)$|\1|p' -- "${dir:?}/bazel.out.tmp")"

# Replace test log directory in the output with a fixed value.  This gets rid
# of the arbitrary build configuration directory.
sed -E -e "s|${testlogs}|%ROOTDIR%/bazel-out/k8-fastbuild/testlogs|" -- \
  "${dir:?}/bazel.out.tmp" > "${dir:?}/bazel.out"

(
  set -eu
  echo '# [[file:detangle.org::coverage.dat][coverage.dat]]'
  cat "${dat:?}"
  echo '# coverage.dat ends here'
) > "${dir:?}/coverage.dat" || exit

cp -- "${org:?}" "${dir:?}/detangle.org" || exit
emacs --quick --batch --load='ob-tangle' --visit="${dir:?}/bazel.out" \
  --eval='(setq org-src-content-indentation 0)' --funcall='org-babel-detangle' \
  --eval='(save-some-buffers t)' || exit
emacs --quick --batch --load='ob-tangle' --visit="${dir:?}/coverage.dat" \
  --eval='(setq org-src-content-indentation 0)' --funcall='org-babel-detangle' \
  --eval='(save-some-buffers t)' || exit
cp -- "${dir:?}/detangle.org" "${org:?}" || exit

echo 'Successfully refreshed coverage.org.'

rm -r -f -- "${dir}"
