#!/usr/bin/env ruby
# frozen_string_literal: true

require_relative '../config/bundler_setup'
require 'fileutils'

require_relative '../spec/support/helpers/gitaly_setup'

# This script assumes tmp/tests/gitaly already contains the correct
# Gitaly version. We just have to compile it.
# We have this separate script for that to avoid bundle
# poisoning in CI. This script should only be run in CI.
class GitalyTestBuild
  include GitalySetup

  def run
    # If we have the binaries from the cache, we can skip building them again
    if File.exist?(tmp_tests_gitaly_bin_dir)
      GitalySetup::LOGGER.debug "Gitaly binary already built. Skip building...\n"
    else
      abort 'gitaly build failed' unless build_gitaly
    end

    ensure_gitlab_shell_secret!

    # Starting gitaly further validates its configuration
    gitaly_pid = start_gitaly(:gitaly)
    gitaly2_pid = start_gitaly(:gitaly2)
    praefect_pid = start_praefect
    Process.kill('TERM', gitaly_pid)
    Process.kill('TERM', gitaly2_pid)
    Process.kill('TERM', praefect_pid)
  end
end

GitalyTestBuild.new.run
