#!/bin/bash --norc
set -euo pipefail

#
# set-visibility-from-rdeps.sh //path/to/package:target
#
# Set the `visibility` property of `target` to the result of the bazel query
# `allrdeps(//path/to/package:target, 1)` in the BUILD file found at
# `path/to/package/BUILD`.
#

function target_to_package() {
  sed -e 's#\(.*\):.*#\1#'
}

target="$1"
package="$(echo "$target" | target_to_package)"

visibility=$(
  bazel query --universe_scope=//... --order_output=no "allrdeps($target, 1)" |
    target_to_package |
    xargs -I{} echo {}:__pkg__ |
    grep -v "$package:__pkg__" |
    sort -u |
    tr "\n" " "
)

buildozer "set visibility ${visibility[@]}" "$target"
