{%- set ns = project_name -%}
---
apiVersion: v1
kind: Service
metadata:
  name: database-server
  namespace: {{ ns }}
  labels:
    app: database-server
    app.kubernetes.io/name: freva
    app.kubernetes.io/instance: database-server
    app.kubernetes.io/component: web-app
    app.kubernetes.io/part-of: freva
    app.kubernetes.io/version: {{ db_version }}
    app.kubernetes.io/managed-by: ansible
    freva.org/stateful: 'true'
    freva.org/tier: database
spec:
  type: ClusterIP
  selector:
    app: database-server
  ports:
    - port: 3306
      targetPort: 3306
      name: mysql

---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: database-server
  namespace: {{ ns }}
  labels:
    app: database-server
    app.kubernetes.io/name: freva
    app.kubernetes.io/instance: database-server
    app.kubernetes.io/component: web-app
    app.kubernetes.io/part-of: freva
    app.kubernetes.io/version: {{ db_version }}
    app.kubernetes.io/managed-by: ansible
    freva.org/stateful: 'true'
    freva.org/tier: database
spec:
  serviceName: database-server
  replicas: 1
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 0
      maxUnavailable: 1
  selector: { matchLabels: { app: database-server } }
  template:
    metadata:
      name: database-server
      namespace: {{ ns }}
      labels:
        app: database-server
        app.kubernetes.io/name: freva
        app.kubernetes.io/instance: database-server
        app.kubernetes.io/component: web-app
        app.kubernetes.io/part-of: freva
        app.kubernetes.io/version: {{ db_version }}
        app.kubernetes.io/managed-by: ansible
        freva.org/stateful: 'true'
        freva.org/tier: database
    spec:
      securityContext: { fsGroup: {{ fs_group }} }
      containers:
        - name: mysql
          image: ghcr.io/freva-org/freva-mysql:{{ db_version }}
          imagePullPolicy: {{ image_pull_policy }}
          ports: [{ containerPort: 3306, name: mysql }]
          resources: {{ resources['database-server'] }}
          env:
            - name: ROOT_PW
              valueFrom: { secretKeyRef: { name: freva-secrets, key: MYSQL_ROOT_PASSWORD } }
            - name: MYSQL_ROOT_PASSWORD
              valueFrom: { secretKeyRef: { name: freva-secrets, key: MYSQL_ROOT_PASSWORD } }
            - { name: MYSQL_USER, value: "{{ db_user }}" }
            - name: MYSQL_PASSWORD
              valueFrom: { secretKeyRef: { name: freva-secrets, key: MYSQL_PASSWORD } }
            - { name: MYSQL_DATABASE, value: "{{ db }}" }
            - { name: HOST, value: "{{ db_host }}" }
            - { name: PROJECT, value: "{{ project_name }}" }
          volumeMounts:
            - { name: db-data, mountPath: /data/db }
      volumes:
        - name: db-data
          persistentVolumeClaim: { claimName: db-data }
