class ClusterLoginActivitySyncJob < ApplicationJob
  queue_as :default

  def perform
    clusters = Core::Cluster.all

    clusters.each do |cluster|
      connected = initialize_connection(cluster)

      if connected
        run_on_cluster "sudo /usr/octo/sync_logins"
      end
    end
  end

  private
    def initialize_connection(cluster)
      begin
        @connection_to_cluster = Net::SSH.start(cluster.host,
                                                cluster.admin_login,
                                                keys: [mock_ssh_key_path(cluster.private_key)])
        true
      rescue => e
        logger.info "ClusterLoginActivitySync error: #{e.message})."
        false
      end
    end

    def run_on_cluster(command, log_result = true)
      cluster.log("\t command: #{command}", project)

      result =
        connection_to_cluster ?
          connection_to_cluster.exec!(command) :
          'Failed to connect cluster'

      cluster.log("\t  result: #{result}", project) if log_result
      result
    end

    def mock_ssh_key_path(key)
      path = "/tmp/octo-#{SecureRandom.hex}"
      File.open(path, "wb") { |f| f.write key }
      path
    end
end
