#!/bin/bash
set -e

NAMESPACE="kube-system"
DS_NAME="eks-pod-identity-agent"
PATCH_KEY="eks.amazonaws.com/nodegroup"
PATCH_OPERATOR="NotIn"
PATCH_VALUE="x-compute"

# Pre-check: Verify if a match expression with the given key, operator, and value already exists.
if kubectl get ds "${DS_NAME}" -n "${NAMESPACE}" -o json | jq -e '
  any(
    .spec.template.spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms[]?
    .matchExpressions[]?; 
    .key=="'"${PATCH_KEY}"'" and .operator=="'"${PATCH_OPERATOR}"'" and (.values | index("'"${PATCH_VALUE}"'"))
  )
' >/dev/null; then
  echo "Patch already applied. Exiting without changes."
  exit 0
fi

# Apply JSON patch to append the new node affinity match expression.
kubectl patch daemonset "${DS_NAME}" -n "${NAMESPACE}" --type='json' -p='[
  {
    "op": "add",
    "path": "/spec/template/spec/affinity/nodeAffinity/requiredDuringSchedulingIgnoredDuringExecution/nodeSelectorTerms/0/matchExpressions/-",
    "value": {
      "key": "eks.amazonaws.com/nodegroup",
      "operator": "NotIn",
      "values": ["x-compute"]
    }
  }
]'

echo "Patch applied successfully."
