#!/usr/bin/env ruby
# frozen_string_literal: true

require 'json'
require 'nokogiri'

def teamcity_fail(message, details: nil, hard_fail: true)
  puts "####teamcity[buildProblem description='#{message}']"
  abort details if !details.nil? && hard_fail
  exit if hard_fail
end

def teamcity_success(message, force_exit: false)
  puts "##teamcity[buildStatus status='SUCCESS' text='#{message}']"
  exit if force_exit
end

benchmark = 79
coverage_xml_path = 'coverage/clover.xml'

teamcity_fail 'CodeCov: FAIL - No coverage data. This is most likely due to a Unit Test failure.' unless File.exist?(coverage_xml_path)

coverage_xml = File.open(coverage_xml_path) { |f| Nokogiri::XML(f) }
metrics = coverage_xml.xpath('//project//metrics')[0]
statements = metrics.attr('statements').to_f
covered_statements = metrics.attr('coveredstatements').to_f

coverage = (covered_statements / statements * 100).round(2)

unless coverage > benchmark
  teamcity_fail "CodeCov: FAIL - Line coverage of #{coverage}% is below the #{benchmark}% benchmark"
end

# we pass!
teamcity_success "CodeCov: PASS - #{coverage}% line coverage"
