{{- range $nodeGroupOverrides := .Values.nodeGroups }}
{{- $nodeGroup := deepCopy $.Values.nodeGroupDefaults | mustMerge $nodeGroupOverrides }}
---
apiVersion: cluster.x-k8s.io/v1beta1
kind: MachineDeployment
metadata:
  name: {{ include "openstack-cluster.componentName" (list $ $nodeGroup.name) }}
  labels:
    {{- include "openstack-cluster.componentLabels" (list $ "worker") | nindent 4 }}
    capi.stackhpc.com/node-group: {{ $nodeGroup.name }}
  {{- if $nodeGroup.autoscale }}
  {{-
    $machineCountMin := $nodeGroup.machineCountMin |
      required (printf "no minimum machine count specified for node group '%s'" $nodeGroup.name)
  }}
  {{- if lt $machineCountMin 1.0 }}
  {{- fail "autoscaling node groups with a minimum machine count < 1 are not currently supported" }}
  {{- end }}
  {{-
    $machineCountMax := $nodeGroup.machineCountMax |
      required (printf "no maximum machine count specified for node group '%s'" $nodeGroup.name)
  }}
  {{- if lt $machineCountMax $machineCountMin }}
  {{- fail (printf "maximum machine count < minimum machine count for node group '%s'" $nodeGroup.name) }}
  {{- end }}
  annotations:
    cluster.x-k8s.io/cluster-api-autoscaler-node-group-min-size: {{ quote $machineCountMin }}
    cluster.x-k8s.io/cluster-api-autoscaler-node-group-max-size: {{ quote $machineCountMax }}
  {{- end }}
spec:
  clusterName: {{ include "openstack-cluster.clusterName" $ }}
  {{- if not $nodeGroup.autoscale }}
  replicas: {{ $nodeGroup.machineCount | required (printf "no machine count specified for node group '%s'" $nodeGroup.name) }}
  {{- end }}
  strategy: {{ toYaml $nodeGroup.rolloutStrategy | nindent 4 }}
  selector:
    matchLabels:
      {{- include "openstack-cluster.componentSelectorLabels" (list $ "worker") | nindent 6 }}
      capi.stackhpc.com/node-group: {{ $nodeGroup.name }}
  template:
    metadata:
      labels:
        {{- include "openstack-cluster.componentSelectorLabels" (list $ "worker") | nindent 8 }}
        capi.stackhpc.com/node-group: {{ $nodeGroup.name }}
    spec:
      clusterName: {{ include "openstack-cluster.clusterName" $ }}
      version: {{ $.Values.global.kubernetesVersion }}
      {{- with $nodeGroup.failureDomain }}
      failureDomain: {{ . }}
      {{- end }}
      bootstrap:
        configRef:
          apiVersion: bootstrap.cluster.x-k8s.io/v1beta1
          kind: KubeadmConfigTemplate
          name: {{ include "openstack-cluster.nodegroup.kct.name" (list $ $nodeGroup) }}
      infrastructureRef:
        apiVersion: infrastructure.cluster.x-k8s.io/v1alpha6
        kind: OpenStackMachineTemplate
        name: {{ include "openstack-cluster.nodegroup.mt.name" (list $ $nodeGroup) }}
      nodeDrainTimeout: {{ $nodeGroup.nodeDrainTimeout }}
{{- end }}