# This package contains an external repository that the Android rules
# depend on at runtime. This is an interim solution to extract dependencies
# out from the Bazel binary to minimize its size. The final goal is to
# extract all Android rules and tools out of Bazel and into rules_android
# and tools_android.

load("@rules_pkg//pkg:tar.bzl", "pkg_tar")
load("//tools/android:android_genrule.bzl", "android_genrule")

filegroup(
    name = "srcs",
    srcs = [
        "BUILD.android_tools",
        "BUILD.bazel",
        "WORKSPACE.android_tools",
    ],
    visibility = [
        "//tools/android:__pkg__",
    ],
)

# :android_tools creates a tarball containing the outputs of this genrule.
genrule(
    name = "strip_android_tools_suffix",
    srcs = [
        "BUILD.android_tools",
        "WORKSPACE.android_tools",
    ],
    outs = [
        "BUILD",
        "WORKSPACE",
    ],
    cmd = """
    cp $(location BUILD.android_tools) $(location BUILD) && \
    cp $(location WORKSPACE.android_tools) $(location WORKSPACE)
    """,
    tags = [
        "manual",
        "no_windows",
    ],
)

genrule(
    name = "gen_version_txt",
    outs = ["version.txt"],
    cmd = """
embed_label="$$(grep BUILD_EMBED_LABEL bazel-out/stable-status.txt | cut -d ' ' -f 2-)"
if [[ -z "$$embed_label" ]]; then
  # this happens when building for tests
  version="not_set"
  bazel_version="not_set"
  bazel_repo_commit="not_set"
elif [[ "$$embed_label" =~ ^[0-9]+[.][0-9]+[.][0-9]+\\ [0-9]+[.][0-9]+[.][0-9]+(-pre[.][0-9]{8}[.][0-9]+)?\\ [0-9a-f]{40}$$ ]]; then
  version="$$(echo $$embed_label | cut -d ' ' -f 1)"
  bazel_version="$$(echo $$embed_label | cut -d ' ' -f 2)"
  bazel_repo_commit="$$(echo $$embed_label | cut -d ' ' -f 3)"
else
  echo "bad format for --embed_label"
  exit 1
fi

cat > $@ << EOF
bazel_android_tools_version $$version
bazel_repo_commit $$bazel_repo_commit
built_with_bazel_version $$bazel_version
EOF
""",
    stamp = True,
)

# Needs to switch to dependencies to an android config.
android_genrule(
    name = "desugar_jdk_libs",
    srcs = ["@desugar_jdk_libs"],
    out = "desugar_jdk_libs.jar",
    cmd = "cp $< $@",
    platform = "//tools/android:arm64-v8a",
)

pkg_tar(
    name = "android_tools",
    srcs = [
        "BUILD",
        "WORKSPACE",
        ":desugar_jdk_libs.jar",
        ":version.txt",
        "//src/java_tools/import_deps_checker/java/com/google/devtools/build/importdeps:ImportDepsChecker_deploy.jar",
    ],
    remap_paths = {
        "src/java_tools/import_deps_checker/java/com/google/devtools/build/importdeps:ImportDepsChecker_deploy.jar": "ImportDepsChecker_deploy.jar",
    },
    visibility = ["//src/test/shell/bazel:__subpackages__"],
)
