variable "consul_address" {
  type        = string
  description = "address of consul server for dynamic scraping"
}

# resource "nomad_job" "exporters" {
#   hcl2 {
#     enabled = true
#   }
#
#   jobspec = file("${path.module}/exporters.nomad")
# }

data "consul_nodes" "all-nodes" {
  query_options {
    datacenter = "dc1"
  }
}

resource "nomad_job" "prometheus" {
  hcl2 {
    enabled = true
    vars = {
      # TODO: May not need this because we have an env variable for that
      # "consul_address" = "${var.consul_address}",
      # TODO: Should this be a list?
      "consul_address" = "http://${data.consul_nodes.all-nodes.nodes[0].address}:8500",
    }
  }

  jobspec = file("${path.module}/prometheus.nomad")
}

resource "nomad_job" "grafana" {
  hcl2 {
    enabled = true
  }

  jobspec = templatefile("${path.module}/grafana.nomad", {
    module_path = "${path.module}"
  })
}

resource "consul_config_entry" "prometheus_intent" {
  name = "prometheus"
  kind = "service-intentions"

  config_json = jsonencode({
    Sources = [
      {
        Action     = "allow"
        Name       = "grafana"
        Precedence = 9
        Type       = "consul"
      },
    ]
  })
}

# resource "consul_config_entry" "envoy_prometheus_bind" {
#   name = "global"
#   kind = "proxy-defaults"
#
#   config_json = jsonencode({
#     "envoy_prometheus_bind_addr" = "0.0.0.0:9102"
#   })
# }