#!/usr/bin/env bash
set -euo pipefail

function push_target() {
  target="$1"
  shift
  for filter in "$@"; do
    if ! [[ $target =~ $filter ]]; then
      return 1
    fi
  done
  return 0
}

tag="$(date --utc +%Y%m%dT%H%M%S)"

builtin cd "$(dirname "${BASH_SOURCE[0]}")"
builtin cd "$(bazel info workspace 2>/dev/null)"

targets="$(
  bazel query '//mapping/component/backfill/images/...' 2>/dev/null |
  grep --extended-regexp ':push_.*_image$'
)"

for target in ${targets[@]}; do
  if ! push_target "$target" "$@"; then
    continue
  fi

  echo $target
  (
    set -x
    bazel run --define="mapping_backfill_image_tag=$tag" "$target"
    bazel run --define="mapping_backfill_image_tag=latest" "$target"
  )
done
