#!/bin/bash

set -euo pipefail

if [ "$USER" != "estevens" ]
then
    echo "Please do not run this script or add/change entries in pre_existing_py2_targets.bzl (removing entries is okay). See https://git.zooxlabs.com/zooxco/driving/tree/master/build/python#if-you-absolutely-must-add-new-python-2-only-targets for instructions."
    exit
fi

echo "# GENERATED FILE DO NOT EDIT" > tools/aspects/py2_only_reason_needed/pre_existing_py2_targets.bzl
echo "# No PR should add or edit lines in this file. Removing lines is fine." >> tools/aspects/py2_only_reason_needed/pre_existing_py2_targets.bzl
echo "" >> tools/aspects/py2_only_reason_needed/pre_existing_py2_targets.bzl
echo "pre_existing_py2_targets = {" >> tools/aspects/py2_only_reason_needed/pre_existing_py2_targets.bzl

bazel query "attr('python_version', 'PY2', //...) except attr('tags' ,'has_py3_version', //...) except attr('tags' ,'has_py2_only_reason', //...)" | sort -d | sed -e 's/\(.*\)/    Label("\1"): True,/g' >> tools/aspects/py2_only_reason_needed/pre_existing_py2_targets.bzl
bazel query "attr('srcs_version', 'PY2', kind('py_library', //...)) except attr('srcs_version', 'PY2AND3', //...) except attr('generator_function', 'proto_library', //...) except attr('tags' ,'has_py2_only_reason', //...)" | sort -d | sed -e 's/\(.*\)/    Label("\1"): True,/g' >> tools/aspects/py2_only_reason_needed/pre_existing_py2_targets.bzl

echo "}" >> tools/aspects/py2_only_reason_needed/pre_existing_py2_targets.bzl
