#!/bin/bash

targets=${1:-...}

function tag_target() {
  local tag=$1
  local target=$2

  if buildozer "add tags $tag" $target
  then
    if bazel build --nobuild $target 
    then
      A="$(bazel query 'attr(tags, offline-only, deps(set(//vehicle:l3_deploy_package //bin/...)))')"
      B="$(bazel query 'attr(tags, no-ccb, deps(set(//ci:ccb_regulated_targets)))')"
      if [ -z "$A" ] && [ -z "$B" ]
      then
        git add -u
      else
        echo "Bazel queries failed"
        echo "$A"
        echo "$B"
        git checkout .
      fi
    else
      echo "Build failed"
      git checkout .
    fi
  fi
}

echo "Calculating offline targets"
time bazel query "let a = kind(rule, set($targets) - deps(set(//vehicle:l3_deploy_package //bin/...)) - set(//vehicle:l3_deploy_package_tar_gz //vehicle:l3_deploy_package_tar)) in (\$a - kind(test, \$a)) - attr(tags, no-ccb, \$a) - attr(tags, offline-only, \$a) - attr(testonly, 1, \$a)" | grep -v '^@' > offline.txt

echo "Adding offline-only tag"
for target in $(cat offline.txt)
do
  tag_target "offline-only" $target
done

#echo "Calculating no-ccb targets"
#time bazel query "let a = kind(rule, set($targets) - deps(set(//vehicle:l3_ccb_regulated_package //bin/...)) - set(//vehicle:l3_deploy_package_tar_gz //vehicle:l3_deploy_package_tar)) in \$a - (kind(test, \$a) union attr(tags, offline-only, \$a) union attr(tags, no-ccb, \$a) union attr(testonly, 1, \$a))" | grep -v '^@' > no_ccb.txt
#
#echo "Adding no-ccb tag"
#for target in $(cat no_ccb.txt)
#do
#  tag_target "no-ccb" $target
#done
