# frozen_string_literal: true

# Copyright 2019 Google LLC
#
# 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.


require "bundler/gem_tasks"
require "rubocop/rake_task"
require "rake/testtask"
require_relative "../shared/gem_defaults"

RuboCop::RakeTask.new # Configuration is in .rubocop.yml
Rake::TestTask.new :test do |t|
  t.libs << "test"
  t.libs << "lib"
  t.test_files = FileList["test/**/*_test.rb"]
end

desc "Run the CI build"
task :ci do
  puts "\nBUILDING gapic-generator-ads\n"
  puts "\ngapic-generator-ads rubocop\n"
  Rake::Task[:rubocop].invoke
  puts "\ngapic-generator-ads test\n"
  Rake::Task[:test].invoke
end

libs = [:googleads]

desc "Update the proto binary dumps which are used to generate templates"
task :bin do
  Rake::Task["bin:templates"].invoke
end
namespace :bin do |namespace|
  desc "Update the proto binary dumps for the templates"
  task :templates do
    libs.each do |lib|
      task = namespace[lib]
      puts "Invoking #{task.name}"
      task.invoke
    end
  end

  libs.each do |lib|
    desc "Update the proto binary dumps for #{lib}"
    task lib do
      update_templates_proto_bins lib
    end
  end
end

desc "Generate the expected output for tests"
task :gen do
  Rake::Task["gen:templates"].invoke
end
namespace :gen do |namespace|
  desc "Generate the expected output for template tests"
  task :templates do
    libs.each do |lib|
      task = namespace[lib]
      puts "Invoking #{task.name}"
      task.invoke
    end
  end

  libs.each do |lib|
    desc "Generate the expected output for #{lib}"
    task lib do
      generate_ads_templates lib
    end
  end
end

desc "Start an interactive shell."
task :console do
  require "irb"
  require "irb/completion"
  require "pp"

  $LOAD_PATH.unshift "lib"

  ARGV.clear
  IRB.start
end

desc "Build the docker image."
task :image, :name do |_t, args|
  image_name = args[:name] || "ruby-gapic-generator-ads"
  sh "docker build --no-cache -t #{image_name}:$(git rev-parse HEAD) ."
end
namespace :image do
  desc "Build the docker image using the local base image code"
  task :local, :name do |_t, args|
    image_name = args[:name] || "ruby-gapic-generator-ads"
    mkdir_p "tmp"
    base_source_dir = File.join File.dirname(__dir__), "gapic-generator"
    base_tmp_dir = File.join __dir__, "tmp", "gapic-generator"
    rm_rf base_tmp_dir
    cp_r base_source_dir, base_tmp_dir
    sh "docker build --no-cache -t #{image_name}:$(git rev-parse HEAD) ."
    rm_r base_tmp_dir
  end
end

task :release_gem do
  Rake::Task["build"].invoke
  Rake::Task["release:rubygem_push"].invoke
end

def generate_ads_templates service
  puts "Running templates generation for #{service}"
  require "fileutils"
  require "gapic/generators/ads_generator"

  target_path = File.expand_path File.join("expected_output", String(service))
  FileUtils.rm_rf target_path
  FileUtils.mkdir_p target_path

  protoc_cmd = [
    "grpc_tools_ruby_protoc",
    "-I ../shared/protos",
    "-I ../shared/api-common-protos",
    "-I ../shared/googleapis",
    "--ruby_gapic_opt=generator=ads",
    "--ruby_out=#{target_path}/lib",
    "--grpc_out=#{target_path}/lib",
    "--ruby_gapic_out=#{target_path}",
    "--ruby_gapic_opt=configuration=../shared/config/#{service}.yml"
  ]

  # Add optional samples paths
  samples = samples_for service
  protoc_cmd << "--ruby_gapic_opt='samples=#{samples.join ';'}'" if samples

  # Add optional grpc service config
  grpc_service_config = grpc_service_config_for service
  unless grpc_service_config.empty?
    protoc_cmd << "--ruby_gapic_opt='grpc-service-config=#{grpc_service_config.join ';'}'"
  end

  # Add optional service.yaml
  service_yaml = service_yaml_for service
  if service_yaml
    protoc_cmd << "--ruby_gapic_opt='service-yaml=#{service_yaml}'"
  end

  # Add the proto files
  protos = protos_for service
  protoc_cmd << protos.join(" ")

  protoc_cmd = protoc_cmd.join " "
  puts protoc_cmd if ENV["VERBOSE"]

  protoc_cmd_output = `#{protoc_cmd}`
  puts protoc_cmd_output if ENV["VERBOSE"]
end

##
# Updates the binary dumps that are used in :gen namespace raketasks
# by calling through to the raketasks defined in `shared`
#
def update_templates_proto_bins service
  Dir.chdir "../shared" do
    Bundler.with_unbundled_env do
      puts "Running binary input file generation for #{service}"
      sh "bundle exec rake gen:#{service}", verbose: false
    end
  end
end

task default: :ci
