
locals {
  common-labels = {
    "vynil.solidite.fr/owner-name" = var.instance
    "vynil.solidite.fr/owner-namespace" = var.namespace
    "vynil.solidite.fr/owner-category" = var.category
    "vynil.solidite.fr/owner-component" = var.component
    "app.kubernetes.io/managed-by" = "vynil"
    "app.kubernetes.io/name" = var.component
    "app.kubernetes.io/instance" = var.instance
  }
  rb-patch = <<-EOF
    - op: replace
      path: /subjects/0/namespace
      value: "${var.namespace}"
    EOF

}
data "kustomization_overlay" "data" {
  common_labels = local.common-labels
  namespace = var.namespace
  resources = [for file in fileset(path.module, "*.yaml"): file if file != "index.yaml" && length(regexall("ClusterRole",file))<1 && length(regexall("APIService",file))<1]
  images {
    name = "ghcr.io/kedacore/keda-metrics-apiserver"
    new_name = "${var.images.metrics.registry}/${var.images.metrics.repository}"
    new_tag = "${var.images.metrics.tag}"
  }
  images {
    name = "ghcr.io/kedacore/keda"
    new_name = "${var.images.operator.registry}/${var.images.operator.repository}"
    new_tag = "${var.images.operator.tag}"
  }
  patches {
    target {
      kind = "Deployment"
      name = "keda-metrics-apiserver"
    }
    patch = <<-EOF
    - op: replace
      path: /spec/template/spec/containers/0/imagePullPolicy
      value: "${var.images.metrics.pull_policy}"
    EOF
  }
  patches {
    target {
      kind = "Deployment"
      name = "keda-operator"
    }
    patch = <<-EOF
    - op: replace
      path: /spec/template/spec/containers/0/imagePullPolicy
      value: "${var.images.operator.pull_policy}"
    EOF
  }
}

data "kustomization_overlay" "data_no_ns" {
  common_labels = local.common-labels
  resources = [for file in fileset(path.module, "*.yaml"): file if file != "index.yaml" && (length(regexall("ClusterRole",file))>0 || length(regexall("APIService",file))>0)]
  patches {
    target {
      kind = "ClusterRoleBinding"
      name = "keda-hpa-controller-external-metrics"
    }
    patch = local.rb-patch
  }
  patches {
    target {
      kind = "ClusterRoleBinding"
      name = "keda-operator"
    }
    patch = local.rb-patch
  }
  patches {
    target {
      kind = "ClusterRoleBinding"
      name = "keda-system-auth-delegator"
    }
    patch = local.rb-patch
  }
  patches {
    target {
      kind = "APIService"
      name = "v1beta1.external.metrics.k8s.io"
    }
    patch = <<-EOF
    - op: replace
      path: /spec/service/namespace
      value: "${var.namespace}"
    EOF
  }
}


