#!/usr/bin/ruby

require 'net/http'
require 'nokogiri'
require 'launchy'
require 'optparse'

options = { api_url: 'https://api.opensuse.org' }
OptionParser.new do |opts|
  opts.banner = "Usage: #{ARGV[0]} [options]"
  opts.on('-b', '--browser', 'Open Browser to show diff') do |v|
    options[:browser] = v
  end
  opts.on('-aAPI_URL', '--api_url=API_URL', 'API URL (default build.o.o)') do |v|
    options[:api_url] = v
  end
end.parse!

def available_revision(api_url)
  uri = URI("#{api_url}/public/build/OBS:Server:Unstable/SLE_15_SP1/x86_64/obs-server")
  result = Net::HTTP.get(uri)
  doc = Nokogiri::XML(result)
  obs_api_filename = doc.xpath('//binary[starts-with(@filename, "obs-api")]/@filename').to_s
  obs_api_filename.match(/obs-api-2\.11~alpha\.\w*\.(?<git>\w*)-(?<release>\w*.)*/)[:git]
end

def deployed_revision(api_url)
  uri = URI("#{api_url}/about")
  result = Net::HTTP.get(uri)
  doc = Nokogiri::XML(result)
  doc.xpath('//commit').first.content
end

url = "https://github.com/openSUSE/open-build-service/compare/#{deployed_revision(options[:api_url])}...#{available_revision(options[:api_url])}"
if options[:browser]
  Launchy.open(url)
else
  result = Net::HTTP.get(URI("#{url}.diff"))
  output = <<~HEREDOC
    ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

    Using #{options[:api_url]}
    Deployed revision: #{deployed_revision(options[:api_url])}
    Available revision: #{available_revision(options[:api_url])}

    ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

    #{result}
  HEREDOC
  puts output
end
