#!/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 = 5

# 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)
    unless (0..10).cover?(priority)
      warn '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!

user = Debci::User.find_or_create_by!(username: requestor)

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