#!/usr/bin/env ruby
# SPDX-License-Identifier: MulanPSL-2.0+
# frozen_string_literal: true

require_relative '../container/defconfig.rb'
set_local_env
require 'optparse'

require_relative '../lib/git_bisect'
require_relative '../lib/mail_bisect_result'

def parse_argv
  items = {}
  ARGV.each do |item|
    key, value = item.split('=', 2)
    if key && value
      items[key] = value
    end
  end
  items
end

op = OptionParser.new do |opts|
  opts.banner = 'Usage: git-bisect bad_job_id=$bad_job_id, error_id=$error_id'

  opts.separator ''
  opts.separator 'bad_job_id: you submit a job to compass-ci and the job has some errors'
  opts.separator 'error_id: you want git bisect a error from the errors that you got'
  opts.separator ''

  opts.on_tail('-h', '--help', 'show the help message') do
    puts opts
    exit
  end
end

op.parse!(ARGV)
items = parse_argv
unless items['bad_job_id'] || items['error_id']
  system 'git-bisect -h'
  exit
end

gb = GitBisect.new(items)
result = gb.find_first_bad_commit
mbr = MailBisectResult.new result
mbr.create_send_email
