begin
  require "cookstyle/chefstyle"
  require "rubocop/rake_task"
  desc "Run Chefstyle tests"
  RuboCop::RakeTask.new(:style) do |task|
    task.options += ["--display-cop-names", "--no-color"]
  end
rescue LoadError
  puts "cookstyle gem is not installed. bundle install first to make sure all dependencies are installed."
end
task default: %i{style}

desc "Refresh project Gemfile.locks (components/gems and omnibus) with the latest dependencies."
task update: ["update:go"] do
  require "bundler"
  Bundler.with_unbundled_env do
    ["./components/gems/", "./omnibus/"].each do |dir|
      Dir.chdir(dir) do
        sh "bundle lock --update --add-platform ruby x64-mingw32 x86-mingw32 x64-mingw-ucrt"
      end
    end
  end
end

namespace :update do
  def run_in_go_container(script)
    wrapper_dir = "components/main-cinc-wrapper"
    repo_root = File.expand_path(__dir__)
    sh(
      "docker", "run", "--rm",
      "-u", "#{Process.uid}:#{Process.gid}",
      "-v", "#{repo_root}:/w",
      "-w", "/w/#{wrapper_dir}",
      "-e", "GOCACHE=/tmp/.gocache",
      "-e", "GOMODCACHE=/tmp/.gomodcache",
      "golang:latest",
      "sh", "-c", script
    )
  end

  desc "Refresh Go module dependencies for components/main-cinc-wrapper (runs in a golang container)."
  task :go do
    run_in_go_container("go get -u ./... && go mod tidy")
  end

  namespace :go do
    desc "Bump Go modules to latest major versions for testing (uses gomajor; rewrites imports)."
    task :major do
      run_in_go_container(
        "go run github.com/icholy/gomajor@latest get all@latest && go mod tidy"
      )
    end
  end
end
