#!/usr/bin/env bash
# Both bazelisk and bazel's native wrapper scripts will attempt to use the well-known executable
# named "tools/bazel" to run Bazel. The path of the original executable is stored in BAZEL_REAL.
set -euo pipefail
shopt -s nullglob

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

# Jump into nix-shell if BAZEL_REAL is set to a /nix/store path and we aren't
# inside our shell yet.
if [[ "${BAZEL_REAL:-}" == /nix/store/* && -z "${MONOGON_NIXOS:-}" ]]; then
  echo "Detected Nix based bazel installation and we are not in a nix-shell, overriding to nix-shell." >&2
  USE_NIX_SHELL=yes
fi

# If the wrapper is called directly we check if nix-shell is available
# to automagically switch into the nix-shell. Otherwise complain and
# exit.
if [[ -z "${BAZEL_REAL:-}" ]]; then
  # If we are already in the nix shell, we just set BAZEL_REAL and continue
  # regular execution. Bazel will be in PATH.
  if [[ -n "${MONOGON_NIXOS:-}" ]]; then
    BAZEL_REAL="$(command -v bazel)"
  elif [[ -x $(command -v nix-shell) ]]; then
    echo "BAZEL_REAL is not set and nix-shell is available, overriding to nix-shell" >&2
    USE_NIX_SHELL=yes
  else
    echo "BAZEL_REAL is not set and nix-shell not available. Please check the setup guide." >&2
    exit 1
  fi
fi

if [[ -n "${USE_NIX_SHELL:-}" ]]; then
  # Jump to project root since bwrap hangs if we aren't there
  cd "${DIR}/../"

  export COMMAND="bazel $*"
  export PWD="$OLDPWD"
  exec nix-shell
fi

prechecks() {
  # Recommend using Bazelisk instead of Bazel's "bazel.sh" wrapper.
  # Skip if we're inside the Nix shell (which uses a customized Bazel build).
  if [[ -z "${BAZELISK_SKIP_WRAPPER:-}" && -z "${MONOGON_NIXOS:-}" ]]; then
    echo "############################################################" >&2
    echo "#  Please use Bazelisk to build the Monorepo. Using Bazel  #" >&2
    echo "#  directly may work, but is not recommended or supported. #" >&2
    echo "############################################################" >&2
  fi

  # Our local user needs write access to /dev/kvm. Warn if this is not the case.
  if ! touch /dev/kvm; then
    echo "###################################################################" >&2
    echo "#  Cannot write to /dev/kvm - please verify permissions.          #" >&2
    echo "#  Most tests require KVM and will not work. Builds still work.   #" >&2
    echo "#  On most systems, add your user to the kvm group and re-login.  #" >&2
    echo "###################################################################" >&2
  fi
}

prechecks

exec -a "$0" "${BAZEL_REAL}" "$@"
