require 'debci/runner/base'
require 'debci/amqp'
require 'debci/backend'

module Debci::Runner
  class Debci < Base
    def select_backend
      ::Debci::Backend.select(job.preferred_backend, job.arch)
    end

    def submit
      queue = ::Debci::AMQP.get_queue(job.arch, job.selected_backend)
      parameters = enqueue_parameters
      message = [job.package.name, job.suite, *parameters].join(" ")
      queue.publish(message, priority: job.priority)
    end

    def enqueue_parameters
      parameters = ['run-id:%s' % job.id]
      if job.trigger
        parameters << "trigger:#{CGI.escape(job.trigger)}"
      end
      Array(job.pin_packages).each do |pin|
        *pkgs, suite = pin
        parameters << "pin-packages:#{suite}=#{pkgs.join(',')}"
      end
      Array(job.extra_apt_sources).each do |name|
        src = ::Debci.extra_apt_sources_list.find(name)
        parameters << "extra-apt-source:#{Base64.strict_encode64(src.entry)}"
        parameters << "signing-key:#{Base64.strict_encode64(src.signing_key)}" if src.signing_key
      end
      if job.autopkgtest
        parameters << "autopkgtest:#{job.autopkgtest}"
      end
      parameters << "backend:#{job.backend}"
      parameters
    end
  end
end
