{{/*
  Machine templates are immutable, so we need to make a new one when the spec changes.
  To do this, we create a new template whenever the checksum of the spec changes.
*/}}
{{- define "openstack-cluster.nodegroup.mt.spec" -}}
{{- $ctx := index . 0 -}}
{{- $nodeGroup := index . 1 -}}
template:
  spec:
    identityRef:
      kind: Secret
      name: {{ include "openstack-cluster.cloudCredentialsSecretName" $ctx }}
    cloudName: openstack
    flavor: {{ $nodeGroup.machineFlavor | required (printf "no flavor specified for node group '%s'" $nodeGroup.name) }}
    {{- with $ctx.Values.machineSSHKeyName }}
    sshKeyName: {{ . }}
    {{- end }}
    {{- with $nodeGroup.machineRootVolume }}
    rootVolume: {{ toYaml . | nindent 6 }}
    {{- end }}
    {{- if $ctx.Values.machineImageId }}
    imageUUID: {{ $ctx.Values.machineImageId }}
    {{- else if $ctx.Values.machineImage }}
    image: {{ tpl $ctx.Values.machineImage $ctx }}
    {{- else }}
    {{- fail "Either machineImage or machineImageId is required" }}
    {{- end }}
    {{- with $nodeGroup.machineNetworking.networks }}
    networks: {{ toYaml . | nindent 6 }}
    {{- end }}
    {{- with $nodeGroup.machineNetworking.ports }}
    ports: {{ toYaml . | nindent 6 }}
    {{- end }}
{{- end }}

{{- define "openstack-cluster.nodegroup.mt.checksum" -}}
{{- include "openstack-cluster.nodegroup.mt.spec" . | sha256sum }}
{{- end }}

{{- define "openstack-cluster.nodegroup.mt.name" -}}
{{- $ctx := index . 0 }}
{{- $nodeGroup := index . 1 }}
{{- $checksum := include "openstack-cluster.nodegroup.mt.checksum" . }}
{{- include "openstack-cluster.componentName" (list $ctx $nodeGroup.name) }}-{{ trunc 8 $checksum }}
{{- end }}

{{- range $nodeGroupOverrides := .Values.nodeGroups }}
{{- $nodeGroup := deepCopy $.Values.nodeGroupDefaults | mustMerge $nodeGroupOverrides }}
---
apiVersion: infrastructure.cluster.x-k8s.io/v1alpha6
kind: OpenStackMachineTemplate
metadata:
  name: {{ include "openstack-cluster.nodegroup.mt.name" (list $ $nodeGroup) }}
  labels:
    {{- include "openstack-cluster.componentLabels" (list $ "worker") | nindent 4 }}
    capi.stackhpc.com/node-group: {{ $nodeGroup.name }}
  annotations:
    capi.stackhpc.com/template-checksum: {{ include "openstack-cluster.nodegroup.mt.checksum" (list $ $nodeGroup) }}
    # We let Cluster API clean up the cluster resources
    # Deleting them ourselves, which CAPI is not expecting, can cause some nasty race conditions
    helm.sh/resource-policy: keep
spec: {{ include "openstack-cluster.nodegroup.mt.spec" (list $ $nodeGroup) | nindent 2 }}
{{- end }}