# Get a purchased add-on
# Required environment: API_ORIGIN, SUBSCRIBER_ACCESS_TOKEN, SUBSCRIBER_ADD_ON_PLAN_ID
# API_ORIGIN is the operator origin, without a /subscriber suffix.
# Makes one request; does not retry or follow redirects. After an uncertain write, check your order/SIM state before repeating.
# Save as addOnPlan_getById.rb; run: ruby addOnPlan_getById.rb (Ruby 2.6+, standard library).
require 'json'
require 'net/http'
require 'uri'

def required(name)
  value = ENV[name]
  raise 'Set ' + name if value.nil? || value.empty?
  value
end
origin = URI(required('API_ORIGIN'))
raise 'API_ORIGIN must be an HTTP(S) origin only' unless %w[http https].include?(origin.scheme) && origin.host && !origin.userinfo && ['', '/'].include?(origin.path) && !origin.query && !origin.fragment
url = URI(origin.to_s.sub(%r{/$}, '') + "/subscriber/add-on_plans/{subscriberAddOnPlanId}".gsub("{subscriberAddOnPlanId}", URI.encode_www_form_component(required("SUBSCRIBER_ADD_ON_PLAN_ID")).gsub('+', '%20')))
request = Net::HTTP::Get .new(url.request_uri)
request['Authorization'] = 'Bearer ' + required('SUBSCRIBER_ACCESS_TOKEN')
begin
  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = url.scheme == 'https'
  http.open_timeout = 30
  http.read_timeout = 30
  http.max_retries = 0 if http.respond_to?(:max_retries=)
  response = http.request(request)
  puts 'HTTP ' + response.code
  text = response.body.to_s
  unless text.empty?
    begin
      puts JSON.pretty_generate(JSON.parse(text))
    rescue JSON::ParserError
      puts text
    end
  end
  exit(response.code.to_i.between?(200, 299) ? 0 : 1)
rescue StandardError => error
  warn 'Request failed: ' + error.message
  exit 1
end
