# PostSync hook to patch longhorn-csi-plugin DaemonSet with control-plane tolerations
# This runs after longhorn-config Application syncs, ensuring CSI plugin can run on all nodes
apiVersion: batch/v1
kind: Job
metadata:
  name: longhorn-patch-csi-tolerations
  namespace: longhorn-system
  annotations:
    argocd.argoproj.io/hook: PostSync
    argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
spec:
  backoffLimit: 3
  template:
    metadata:
      name: patch-csi-tolerations
    spec:
      restartPolicy: Never
      serviceAccountName: longhorn-patch-csi-tolerations
      containers:
      - name: patch
        image: bitnami/kubectl:latest
        command:
        - /bin/bash
        - -c
        - |
          set -euo pipefail
          
          echo "Patching longhorn-csi-plugin DaemonSet with control-plane tolerations..."
          
          kubectl patch daemonset longhorn-csi-plugin -n longhorn-system --type=json -p='[
            {
              "op": "add",
              "path": "/spec/template/spec/tolerations/-",
              "value": {
                "key": "node-role.kubernetes.io/control-plane",
                "operator": "Exists",
                "effect": "NoSchedule"
              }
            }
          ]'
          
          echo "✓ Patch applied successfully"
          
          echo ""
          echo "Waiting for CSI plugin pods to roll out to all nodes..."
          kubectl rollout status daemonset/longhorn-csi-plugin -n longhorn-system --timeout=120s
          
          echo ""
          echo "Final status:"
          kubectl get daemonset longhorn-csi-plugin -n longhorn-system
          kubectl get pods -n longhorn-system -l app=longhorn-csi-plugin -o wide
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: longhorn-patch-csi-tolerations
  namespace: longhorn-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: longhorn-patch-csi-tolerations
  namespace: longhorn-system
rules:
- apiGroups: ["apps"]
  resources: ["daemonsets"]
  verbs: ["get", "patch"]
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["list", "get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: longhorn-patch-csi-tolerations
  namespace: longhorn-system
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: longhorn-patch-csi-tolerations
subjects:
- kind: ServiceAccount
  name: longhorn-patch-csi-tolerations
  namespace: longhorn-system
