locals {
    prometheus = { for k, v in var.monitor.prometheus : k => v if k!="enable" }
    opentelemetry = { for k, v in var.monitor.opentelemetry : k => v if k!="enable" }
    jaeger = { for k, v in var.monitor.jaeger : k => v if k!="enable" }
}

resource "kubernetes_namespace_v1" "monitor-ns" {
  count = ( var.monitor.prometheus.enable || var.monitor.jaeger.enable || var.monitor.opentelemetry.enable )? 1 : 0
  metadata {
    annotations = local.annotations
    labels = local.common-labels
    name = var.monitor.namespace
  }
}

resource "kubectl_manifest" "prometheus" {
  count = var.monitor.prometheus.enable ? 1 : 0
  depends_on = [kubernetes_namespace_v1.monitor-ns]
  yaml_body  = <<-EOF
    apiVersion: "vynil.solidite.fr/v1"
    kind: "Install"
    metadata:
      name: "prometheus"
      namespace: "${var.monitor.namespace}"
      labels: ${jsonencode(local.common-labels)}
    spec:
      distrib: "${var.component}"
      category: "monitor"
      component: "prometheus"
      options: ${jsonencode(local.prometheus)}
  EOF
}

resource "kubectl_manifest" "opentelemetry" {
  count = var.monitor.opentelemetry.enable ? 1 : 0
  depends_on = [kubernetes_namespace_v1.monitor-ns]
  yaml_body  = <<-EOF
    apiVersion: "vynil.solidite.fr/v1"
    kind: "Install"
    metadata:
      name: "opentelemetry"
      namespace: "${var.monitor.namespace}"
      labels: ${jsonencode(local.common-labels)}
    spec:
      distrib: "${var.component}"
      category: "monitor"
      component: "opentelemetry"
      options: ${jsonencode(local.opentelemetry)}
  EOF
}

resource "kubectl_manifest" "jaeger" {
  count = var.monitor.jaeger.enable ? 1 : 0
  depends_on = [kubernetes_namespace_v1.monitor-ns]
  yaml_body  = <<-EOF
    apiVersion: "vynil.solidite.fr/v1"
    kind: "Install"
    metadata:
      name: "jaeger"
      namespace: "${var.monitor.namespace}"
      labels: ${jsonencode(local.common-labels)}
    spec:
      distrib: "${var.component}"
      category: "monitor"
      component: "jaeger"
      options: ${jsonencode(local.jaeger)}
  EOF
}
