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

require 'faraday'
require 'faraday_middleware'
require 'json'

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

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

def teamcity_message(message)
  puts "##teamcity[message text='#{message}']"
end

def teamcity_parameter(key, value)
  puts "##teamcity[setParameter name='#{key}' value='#{value}']"
end

GURU_ADDR = ENV['GURU_ADDR'].freeze
MAX_AGE = ENV['MAX_AGE'].to_i.freeze

expires_time = Time.now - MAX_AGE
count = 0
max = 200

puts "Looking for channels older than #{expires_time} (#{expires_time.to_i})"

guru = Faraday.new(url: GURU_ADDR) do |conn|
  conn.response :json, content_type: 'application/json'
  conn.adapter :net_http
  conn.headers = {
    Authorization: "Bearer #{ENV['S2S_TOKEN']}",
    UploadKey: ENV['GURU_ACCESS_KEY']
  }
end

res = guru.get '/release/channels'
teamcity_fail "Guru returned with code #{res.status}" unless res.status == 200

hide_channels = []

res.body.each do |channel|
  next if channel['id'] == 'master' # never purge master
  next unless channel['updatedTimestamp'] < (expires_time.to_i * 1000)

  teamcity_message "Hide channel #{channel['id']}"
  hide_channels.push channel['id']
  count += 1
  break unless count < max
  # clean_res = guru.post "release/#{channel['id']}/remove-release-channel"
  # teamcity_fail "Guru returned with code #{clean_res.status}" unless clean_res.status == 200
  # sleep GURU_THROTTLE
end

unless hide_channels.empty?
  payload = { IDs: hide_channels }

  clean_res = guru.post do |req|
    req.url '/release/remove-release-channels'
    req.headers['Content-Type'] = 'application/json'
    req.body = payload.to_json
  end

  teamcity_fail "Guru returned with code #{clean_res.status}" unless clean_res.status == 200
end

teamcity_success "#{count} channels removed out of #{res.body.count}"
# teamcity_fail "This is a forced failure.  #{count} channels removed out of #{res.body.count}"
