# Runs the given command on all vision machines in succession.
# Usage: vision-each <command>
# e.g. vision-each ssh -T git@github.com
function vision-each {
  echo -e "\e[33mNOTE: This does not source .bashrc so some functions/aliases might not be available.\e[0m"

  source "$ZOOX_WORKSPACE_ROOT"/vehicle/common/environment/robot_name/robot_name.sh
  local robot_name; robot_name=$(robot_name)

  local vision_count; vision_count=$(
    /etc/zoox/calibration/hardware_configuration.py --vision_machine_count $(robot_name)
  )

  if [ "$?" -ne 0 ]; then
    echo -e "\e[31mFailed to get vision count. Defaulting to 6.\e[0m"
    vision_count=6
  fi

  local machine;

  for machine_number in $(seq 1 "$vision_count"); do
    machine="vision${machine_number}"
    # Print out the machine name in red.
    echo -e "\e[32m$machine\e[0m"
    ssh -t "$machine" "$@"
    exit_code="$?"

    if [[ "$exit_code" != 0 ]]; then
      echo -e "\e[31mCommand failed on $machine: $exit_code\e[0m"
    fi
  done
}

# Override `bazel_root` from scripts/shell/bazel/functions.sh
# as these scripts are being loaded from the build in /opt/zoox
# on vehicle which is not a Bazel workspace.
# Instead we'll just assume that it's the `driving` directory in the
# user's home directory which is true on vehicle.
function bazel_root() {
    ws_root="/home/$USER/driving"
    if [[ -d "$ws_root" ]]; then
        echo "$ws_root"
        return 0
    fi

    echo bazel_root: Workspace root could not be found! 1>&2;
    return 1
}
