apiVersion: apps/v1
kind: Deployment
metadata:
  name: hydra-secret-sync
spec:
  replicas: 1
  selector:
    matchLabels:
      app: hydra-secret-sync
  template:
    metadata:
      labels:
        app: hydra-secret-sync
    spec:
      containers:
      - name: sync
        image: lachlanevenson/k8s-kubectl:v1.16.3
        command: ["/bin/sh", "-c"]
        args:
        - |
            set -e
            randPwd() {
              cat /dev/urandom | base64 | head -c 32 | LC_ALL=C tr -dc 'A-Za-z0-9'
            }
            mkdir /tmp/secret
            DSN="$(kubectl get secret hydra -o jsonpath='{.data.dsn}' | base64 -d)"
            echo -n "postgres://$(cat /tmp/postgres/username):$(cat /tmp/postgres/password)@${PG_HOST}:${PG_PORT}/${PG_DB}" > /tmp/secret/dsn
            if [ "$DSN" != "$(cat /tmp/secret/dsn)" ]; then
              # Rotate hydra secrets whenever postgres dsn changes
              set -ex
              for KEY in secretsSystem secretsCookie; do
                randPwd > /tmp/secret/$KEY
                kubectl get secret hydra -o jsonpath="{.data.$KEY}" | base64 -d > /tmp/previous-secret-val
                # TODO: remove very old secrets?!
                [ ! "$(cat /tmp/previous-secret-val)" ] || (echo ,; cat /tmp/previous-secret-val) >> /tmp/secret/$KEY
                rm /tmp/previous-secret-val
              done
              kubectl create secret generic hydra --dry-run -o yaml --from-file=/tmp/secret/dsn --from-file=/tmp/secret/secretsSystem --from-file=/tmp/secret/secretsCookie | kubectl apply -f -
              rm -rf /tmp/secret
            else
              echo dsn unchanged
            fi
            echo synced > /tmp/synced
            while true; do sleep 86400; done
        env:
        - name: NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: PG_HOST
          value: pg-cluster
        - name: PG_PORT
          value: "5432"
        - name: PG_DB
          value: hydra
        readinessProbe:
          exec:
            command:
              - /bin/cat
              - /tmp/synced
          initialDelaySeconds: 7
          periodSeconds: 5
        resources:
          requests:
            cpu: "10m"
            memory: "16Mi"
          limits:
            cpu: "200m"
            memory: "64Mi"
        volumeMounts:
        - name: postgres-credentials
          mountPath: /tmp/postgres
      volumes:
      - name: postgres-credentials
        secret:
          secretName: hydra.pg-cluster.credentials
      terminationGracePeriodSeconds: 3
      automountServiceAccountToken: true
      serviceAccountName: hydra-secret-sync
