# Copyright 2016 The Closure Rules Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

def _webfiles_external(repository_ctx):
  """Downloads HTTP archive and creates a webfiles rule."""
  name = repository_ctx.attr.generated_rule_name or repository_ctx.name
  lines = ["# DO NOT EDIT: generated by webfiles_external()", ""]
  if repository_ctx.attr.default_visibility:
    lines.append("package(default_visibility = %s)" % (
        repository_ctx.attr.default_visibility))
    lines.append("")
  lines.append("licenses(%s)" % repr(repository_ctx.attr.licenses))
  lines.append("")
  lines.append("load(\"@io_bazel_rules_closure//closure:" +
               "defs.bzl\", \"webfiles\")")
  lines.append("")
  lines.append("webfiles(")
  lines.append("    name = %s," % repr(name))
  for attr in ("srcs",
               "data",
               "path",
               "visibility",
               "exports",
               "suppress",
               "deps"):
    value = getattr(repository_ctx.attr, attr, None)
    if value:
      lines.append("    %s = %s," % (attr, repr(value)))
  if repository_ctx.attr.testonly_:
    lines.append("    testonly = 1,")
  lines.append(")")
  lines.append("")
  extra = repository_ctx.attr.extra_build_file_content
  if extra:
    lines.append(extra)
    if not extra.endswith('\n'):
      lines.append("")
  repository_ctx.download_and_extract(
      repository_ctx.attr.urls,
      "",
      repository_ctx.attr.sha256,
      "",
      repository_ctx.attr.strip_prefix)
  repository_ctx.file("BUILD", "\n".join(lines))

webfiles_external = repository_rule(
    implementation=_webfiles_external,
    attrs={
        "sha256": attr.string(mandatory=True),
        "urls": attr.string_list(mandatory=True, allow_empty=False),
        "licenses": attr.string_list(mandatory=True, allow_empty=False),
        "strip_prefix": attr.string(),
        "path": attr.string(mandatory=True),
        "srcs": attr.string_list(mandatory=True, allow_empty=False),
        "data": attr.string_list(allow_empty=False),
        "deps": attr.string_list(),
        "exports": attr.string_list(),
        "suppress": attr.string_list(),
        "testonly_": attr.bool(),
        "generated_rule_name": attr.string(),
        "default_visibility": attr.string_list(default=["//visibility:public"]),
        "extra_build_file_content": attr.string(),
    })
