<%=
  def underscore(words)
    words = words.to_s.dup
    words.downcase!
    words.gsub! /[^a-z]/, '_'
    words
  end

  def add_gateway(node, locations, options={})
    return nil if options[:ip] == 'REQUIRED'
    gateway = {}
    gateway["capabilities"] = node.openvpn.pick(:ports, :protocols, :user_ips, :adblock, :filter_dns)
    gateway["capabilities"]["transport"] = ["openvpn"]
    gateway["host"] = node.domain.full
    gateway["ip_address"] = options[:ip]
    gateway["capabilities"]["limited"] = options[:limited]
    if node['location']
      location_name = underscore(node.location.name)
      gateway["location"] = location_name
      locations[location_name] ||= node.location
    end
    gateway
  end

  hsh = {}
  hsh["serial"] = 1
  hsh["version"] = 1
  locations = {}
  gateways = []
  configuration = nil
  nodes_like_me[:services => 'openvpn'].each_node do |node|
    if node.openvpn.allow_limited && node.openvpn.allow_unlimited
      gateways << add_gateway(node, locations, :ip => node.openvpn.gateway_address, :limited => false)
      gateways << add_gateway(node, locations, :ip => node.openvpn.second_gateway_address, :limited => true)
    elsif node.openvpn.allow_unlimited
      gateways << add_gateway(node, locations, :ip => node.openvpn.gateway_address, :limited => false)
    elsif node.openvpn.allow_limited
      gateways << add_gateway(node, locations, :ip => node.openvpn.gateway_address, :limited => true)
    end
    if configuration && node.openvpn.configuration != configuration
      log :error, "OpenVPN nodes in the environment `#{node.environment}` have conflicting `openvpn.configuration` values. This will result in bad errors."
    end
    configuration = node.openvpn.configuration
  end
  if gateways.any?
    configuration = configuration.dup
    if configuration['fragment'] && configuration['fragment'] == 1500
      configuration.delete('fragment')
    end
    hsh["gateways"] = gateways.compact
    hsh["locations"] = locations
    hsh["openvpn_configuration"] = configuration
  end
  JSON.sorted_generate hsh
%>