# Copyright (C) 2022 The Android Open Source Project
#
# 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.

import("perfetto.gni")
import("perfetto_cpp_blob_header.gni")

template("perfetto_sql_source_set") {
  action("${target_name}") {
    forward_variables_from(invoker, [ "deps" ])

    out_path = "$target_gen_dir/" + target_name
    rebased_out_path =
        rebase_path(target_gen_dir, root_build_dir) + "/" + target_name

    script = "$perfetto_root_path/tools/touch_file.py"
    args = [
      "--output",
      rebased_out_path,
    ]
    inputs = invoker.sources
    outputs = [ out_path ]
    metadata = {
      perfetto_sql_source_files = inputs
      perfetto_action_type_for_generator = [ "sql_source_set" ]
    }
  }
}

template("perfetto_amalgamated_sql_header") {
  invoker_target = target_name
  gen_txt_file = "$target_gen_dir/${target_name}.txt"

  generated_file("${invoker_target}_generated_file") {
    forward_variables_from(invoker, [ "deps" ])
    outputs = [ gen_txt_file ]
    data_keys = [ "perfetto_sql_source_files" ]
    rebase = root_build_dir
  }

  perfetto_cpp_blob_header(invoker_target) {
    script = "$perfetto_root_path/tools/gen_amalgamated_sql.py"
    sources = [ gen_txt_file ]
    generated_header = "${target_gen_dir}/" + invoker.generated_header
    pass_gen_dir = true
    extra_args = [
      "--namespace",
      "perfetto::trace_processor::${invoker.namespace}",
    ]
    deps = [ ":${invoker_target}_generated_file" ] + invoker.deps
  }

  if (defined(invoker.generate_docs) && invoker.generate_docs &&
      perfetto_build_standalone) {
    action("${invoker_target}_json_docs") {
      deps = [ ":${invoker_target}_generated_file" ]
      deps += invoker.deps

      script = "$perfetto_root_path/tools/gen_stdlib_docs_json.py"
      generated_file = "${target_gen_dir}/stdlib_docs.json"

      args = [
        "--json-out",
        rebase_path(generated_file, root_build_dir),
        "--input-list-file",
        rebase_path(gen_txt_file, root_build_dir),
      ]
      public_configs = [ ":${invoker_target}_config" ]
      inputs = [ gen_txt_file ]
      outputs = [ generated_file ]
    }
  }
}
