# services/mailu/vip-controller.yaml
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: vip-controller
  namespace: mailu-mailserver
imagePullSecrets:
  - name: harbor-regcred
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: vip-controller-role
  namespace: mailu-mailserver
rules:
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["get", "list", "patch", "update"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: vip-controller-binding
  namespace: mailu-mailserver
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: vip-controller-role
subjects:
  - kind: ServiceAccount
    name: vip-controller
    namespace: mailu-mailserver
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: vip-controller
  namespace: mailu-mailserver
spec:
  selector:
    matchLabels:
      app: vip-controller
  template:
    metadata:
      labels:
        app: vip-controller
    spec:
      serviceAccountName: vip-controller
      hostNetwork: true
      nodeSelector:
        mailu.bstein.dev/vip: "true"
      containers:
        - name: vip-controller
          image: registry.bstein.dev/bstein/kubectl:1.35.0
          imagePullPolicy: IfNotPresent
          command:
            - /bin/sh
            - -c
          args:
            - |
              set -e
              while true; do
                if ip addr show end0 | grep -q 'inet 192\.168\.22\.9/32'; then
                  NODE=$(hostname)
                  echo "VIP found on node ${NODE}."
                  kubectl patch deployment mailu-front -n mailu-mailserver --type='merge' \
                    -p "{\"spec\":{\"template\":{\"spec\":{\"nodeSelector\":{\"kubernetes.io/hostname\":\"${NODE}\"}}}}}"
                else
                  echo "No VIP on node ${HOSTNAME}."
                fi
                sleep 60
              done
