#!/usr/bin/env bash

# This script is called by Renovate as a post-upgrade task. It installs
# Bazelisk and then executes tidy in workspaces that have modifications from
# the Renovate upgrade process.

set -o errexit -o nounset -o pipefail

# DEBUG BEGIN
echo >&2 "*** DEBUG $(basename "${BASH_SOURCE[0]}") START ==============="
echo >&2 "*** DEBUG pwd: $(pwd)"
echo >&2 "*** DEBUG git status:"
git status >&2
echo >&2 "*** DEBUG git ls-files -m:"
git ls-files -m >&2
echo >&2 "*** DEBUG git diff --cached --name-only:"
git diff --cached --name-only >&2
echo >&2 "*** DEBUG git diff --name-only HEAD:"
git diff --name-only HEAD >&2 || echo >&2 "*** DEBUG git diff HEAD failed (maybe no commits)"
echo >&2 "*** DEBUG find MODULE.bazel files:"
find . -name MODULE.bazel -not -path './bazel-*' >&2
echo >&2 "*** DEBUG ==============="
set -x
# DEBUG END

# Install Bazelisk, if not found
if which &>/dev/null bazelisk; then
  echo "Bazelisk was found."
  bazelisk="bazelisk"
else
  echo "Bazelisk was not found. Installing..."
  npm install -g @bazel/bazelisk
  npm_root="$(npm root -g)"
  bazelisk="${npm_root}/@bazel/bazelisk/bazelisk-linux_amd64"
fi

# Install build tools
if which &>/dev/null clang; then
  echo "clang was found."
else
  echo "clang was not found. Installing build-essential..."
  # install-tool clang 12.0.0
  install-tool clang-12 12.0.0
fi

# The `interesting_deps` example gates its real dependency list behind two
# environment variables, falling back to an intentionally-invalid
# `not-a-real-package` when either is missing. It is a fixture for the
# `env`/`env_inherit` attrs on the `swift_deps` module extension. That example's
# MODULE.bazel supplies `INTERESTING_DEPS_ENV` via `env`, but it lists
# `INTERESTING_DEPS_INHERIT_ENV` in `env_inherit`, so that one must be present in
# the ambient environment. Its `do_test` exports it for the integration tests;
# export it here so that tidy resolves the real dependencies when Renovate
# modifies that example.
export INTERESTING_DEPS_INHERIT_ENV=1

# Execute tidy for workspaces with modifications The export of CC and the
# --action_env=PATH are specific to running this repository on Linux.
export CC=clang
"${bazelisk}" run --action_env=PATH //:tidy_modified

# DEBUG BEGIN
echo >&2 "*** CHUCK $(basename "${BASH_SOURCE[0]}") Start //:update_swift_packages_for_modified"
# DEBUG END

# Execute swift package update on modified workspaces.
"${bazelisk}" run --action_env=PATH //:update_swift_packages_for_modified

# DEBUG BEGIN
echo >&2 "*** CHUCK $(basename "${BASH_SOURCE[0]}") End //:update_swift_packages_for_modified"
# DEBUG END
