apiVersion: v1
kind: Pod
metadata:
  name: rke2-master-config-updater
  namespace: kube-system
spec:
  hostNetwork: true
  hostPID: true
  hostIPC: true
  nodeSelector:
    node-role.kubernetes.io/master: "true"
  tolerations:
    - effect: NoSchedule
      key: node-role.kubernetes.io/master
      operator: Exists
    - effect: NoSchedule
      key: node-role.kubernetes.io/control-plane
      operator: Exists
  containers:
  - name: config-updater
    image: ubuntu:24.04
    command:
      - /bin/bash
      - -c
      - |
        set -euo pipefail
        echo "=== RKE2 Master Config Updater ==="
        echo "Current config:"
        cat /host/etc/rancher/rke2/config.yaml || echo "Config file not found"

        # Backup existing config
        cp /host/etc/rancher/rke2/config.yaml /host/etc/rancher/rke2/config.yaml.backup-$(date +%Y%m%d-%H%M%S)

        # Add egress-selector-mode if not present
        if ! grep -q "egress-selector-mode" /host/etc/rancher/rke2/config.yaml; then
          echo "Adding egress-selector-mode: disabled"
          echo "egress-selector-mode: disabled" >> /host/etc/rancher/rke2/config.yaml
        else
          echo "egress-selector-mode already present, updating..."
          sed -i 's/^egress-selector-mode:.*/egress-selector-mode: disabled/' /host/etc/rancher/rke2/config.yaml
        fi

        echo ""
        echo "Updated config:"
        cat /host/etc/rancher/rke2/config.yaml

        echo ""
        echo "Restarting rke2-server..."
        nsenter --target 1 --mount --uts --ipc --net --pid -- systemctl restart rke2-server

        echo "Done! Waiting for restart to complete..."
        sleep 10

        echo "Service status:"
        nsenter --target 1 --mount --uts --ipc --net --pid -- systemctl status rke2-server --no-pager
    securityContext:
      privileged: true
    volumeMounts:
    - name: host-root
      mountPath: /host
  volumes:
  - name: host-root
    hostPath:
      path: /
      type: Directory
  restartPolicy: Never
