# frozen_string_literal: true

namespace :karafka do

# Stops a given Karafka process
# @param pidfile [String] path to a pidfile of a process that we're suppose to stop
def stop_karafka(pidfile)
  # If there's no pidfile it means that Karafka is not running
  unless test "cat #{pidfile}"
    info "Karafka is not started: #{pidfile}"
    return
  end

  # Send a kill signal to a given process
  execute "kill -INT `cat #{pidfile}`"

  # And wait until it finishes. We wait because we don't want to start next process until
  # the previous one is stopped. That way we won't have problems with Kafka registering and
  # deregistering processes from topics (although nothing bad would happen. It would just
  # take more time to rebalance)
  loop do
    break unless test "cat #{pidfile}"
    info 'Waiting for Karafka to stop'
    sleep 5
  end
end

desc 'Stop Karafka'
task :stop do
  on roles(fetch(:karafka_role)) do
    for_each_karafka_process do |process_details|
      stop_karafka(process_details[:pidfile])
    end
  end
end

end