#!/usr/bin/ruby

require 'optparse'

require 'debci'
require 'debci/job'

# defaults
trigger = nil
pin_packages = []
run_id = nil
requestor = ENV["USER"] || 'nobody'
arch = Debci.config.arch
suite = Debci.config.suite
priority = 0

# parse command line
optparse = OptionParser.new do |opts|
  opts.banner = "Usage: debci enqueue [OPTIONS] PKG [PKG ...]"
  opts.separator "Options:"

  opts.on('-s', '--suite SUITE', 'sets the suite to test') do |s|
    suite = s
  end

  opts.on('-a', '--arch ARCH', 'sets architecture to test') do |a|
    arch = a
  end

  opts.on('-b', '--backend BACKEND', 'sets the test backend') do |b|
    Debci.config.backend = b
  end

  opts.on('-t', '--trigger TRIGGER', 'associate TRIGGER as the trigger for this test run') do |t|
    trigger = t
  end

  opts.on('-p', '--pin-packages PIN', 'sets package pinning for the test') do |p|
    pin_suite, pin_pkg = p.split('=')
    pin_packages << [pin_pkg, pin_suite]
  end

  opts.on('-r', '--requestor REQUESTOR', 'sets the test requestor') do |r|
    requestor = r
  end

  opts.on('-P', '--priority N', 'sets priority for the test (0-10)') do |p|
    priority = Integer(p)
    if ! (0..10).include?(priority)
      $stderr.puts "E: priority must be a number between 0 and 10"
      exit 1
    end
  end

  opts.on('-i', '--run-id RUNID') do |id|
    run_id = id
  end

end
optparse.parse!

ARGV.each do |pkg|
  job = Debci::Job.new(
    package: pkg,
    arch: arch,
    suite: suite,
    requestor: requestor,
    status: nil,
    trigger: trigger,
    pin_packages: pin_packages,
    run_id: run_id,
  )
  job.save!
  job.enqueue(priority)
  Debci.log "#{pkg} #{suite}/#{arch} requested"
end
