# Static HTTP forward proxy only. This Net::HTTP example does not add outer TLS for Shield.
require 'net/http'
require 'uri'
require 'json'
begin
  proxy = URI(ENV.fetch('QUOTAGUARDSTATIC_URL'))
  raise 'Static URL required' unless proxy.scheme == 'http' && proxy.port == 9293
  target = URI('https://ip.quotaguard.com')
  proxy_class = Net::HTTP::Proxy(proxy.host, proxy.port,
    URI::DEFAULT_PARSER.unescape(proxy.user), URI::DEFAULT_PARSER.unescape(proxy.password))
  http = proxy_class.new(target.host, target.port)
  http.use_ssl = true
  http.open_timeout = 10
  http.read_timeout = 30
  # Avoid Net::HTTP's automatic retry of idempotent requests in this check.
  http.max_retries = 0
  response = http.get(target.request_uri)
  raise 'HTTP status' unless response.code == '200'
  ip = JSON.parse(response.body).fetch('ip')
  pair = ENV.fetch('QG_EXPECTED_IPS').split(',').map(&:strip)
  raise 'Dashboard pair mismatch' unless pair.uniq.length == 2 && pair.include?(ip)
  puts 'Ruby client egress matches dashboard pair'
rescue StandardError
  abort 'Ruby proxy check failed'
end
