<%
# This template can be configure the following way with environment variables
# Environment variables to filter services/instances
#   SERVICES_TAG_FILTER: basic tag filter for service (default HTTP)
#   INSTANCE_MUST_TAG: Second level of filtering (optional, default to SERVICES_TAG_FILTER)
#   INSTANCE_EXCLUDE_TAG: Exclude instances having the given tag (default: canary)
#   EXCLUDE_SERVICES: comma-separated services to exclude (default: consul-agent-http,mesos-slave,mesos-agent-watcher)

  service_tag_filter = ENV['SERVICES_TAG_FILTER'] || nil
  instance_must_tag = ENV['INSTANCE_MUST_TAG'] || service_tag_filter
  instance_exclude_tag = ENV['INSTANCE_EXCLUDE_TAG']

  # Services to hide
  services_blacklist = (ENV['EXCLUDE_SERVICES'] || 'consul-agent-http,mesos-slave,mesos-agent-watcher,mesos-exporter-slave').split(',')
  # Compute the health of a Service
  def compute_state(snode)
    states = ['passing', []]
    snode['Checks'].each do |chk|
      st = chk['Status']
      states[1] << st
      if st == 'critical'
        states[0] = st
      elsif st == 'warning' && states[0] == 'passing'
        states[0] = st
      end
    end
    states
  end
  def compute_attributes(snode)
    w = 100
    snode['Service']['Tags'].each do |tag|
      match = /^weight-([1-9][0-9])*$/.match(tag)
      w = match[1].to_i if match
    end
    attributes = ""
    states = compute_state(snode)
    attributes = "#{attributes} disabled" if states[0] == 'critical'
    if states[0] == 'warning'
      w = w / 8
    end
    attributes = "#{attributes} weight #{w}" if w.positive?
  end
  backends = {}
  tags_per_service = {}
  services(tag: service_tag_filter).each do |service_name, tags|
    if !services_blacklist.include?(service_name) && (instance_must_tag.nil? || tags.include?(instance_must_tag))
      tags_per_service[service_name] = tags.sort
      the_backends = []
      service(service_name).sort {|a,b| a['Node']['Node'] <=> b['Node']['Node'] }.each do |snode|
        tags_of_instance = snode['Service']['Tags'].sort
        if (instance_must_tag.nil? || tags_of_instance.include?(instance_must_tag)) && !tags_of_instance.include?(instance_exclude_tag)
          the_backends << snode if snode['Service']['Port']
        end
      end
      # We add the backend ONLY if at least one valid instance does exists
      backends[service_name] = the_backends
    end
  end
%><%
  json_backends = {}
  backends.each_pair do |service_name, nodes|
    service = {
      name:      service_name,
      count:     nodes.count,
      tags: tags_per_service[service_name],
      instances: [],
    }
    json_backends[service_name] = service
    nodes.each do |snode|
      checks = []
      snode['Checks'].each do |ncheck|
        check = {}
        check['checkid'] = ncheck['ID'] || ncheck['CheckID']
        check['name'] = ncheck['Name']
        check['output'] = ncheck['Output']
        check['status'] = ncheck['Status']
        check['notes'] = ncheck['Notes']
        checks.push(check)
      end
      meta = snode['Service']['Meta']
      server = { frontend_id: "backend_http__#{service_name}",
                 id:      snode['Service']['ID'],
                 name:    snode['Node']['Node'],
                 sMeta:   meta ? meta : {},
                 connect: snode['Service']['Connect'],
                 addr:    snode.service_address,
                 port:    snode['Service']['Port'],
                 tags:    snode['Service']['Tags'],
                 checks:  checks,
                 weights: snode['Service']['Weights'],
      }
      kind_of_service = snode['Service']['Kind']
      service['kind'] = kind_of_service if kind_of_service
      service[:instances] << server
    end
  end
  json_datacenters = datacenters
  json = { services: json_backends, datacenters: json_datacenters, generated_at: Time.now}
%><%= JSON.pretty_generate(json) %>