apiVersion: v1
kind: Service
metadata:
  name: wrestlingdev-mariadb
  labels:
    app: wrestlingdev
spec:
  ports:
    - port: 3306
  selector:
    app: wrestlingdev
    tier: mariadb
  clusterIP: None
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: wrestlingdev-mariadb-pv-claim
  labels:
    app: wrestlingdev
spec:
  # storageClassName: standard
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 20Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: wrestlingdev-mariadb
  labels:
    app: wrestlingdev
spec:
  selector:
    matchLabels:
      app: wrestlingdev
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: wrestlingdev
        tier: mariadb
      annotations:
        prometheus.io/port: "9125"
        prometheus.io/scrape: "true"
    spec:
      containers:
      - image: mariadb:10.3
        name: mariadb
        env:
        - name: MARIADB_ROOT_PASSWORD
          valueFrom:
           secretKeyRef:
             name: wrestlingdev-secrets
             key: dbpassword
        - name: REPLICATION_USER
          valueFrom:
            secretKeyRef:
              name: wrestlingdev-secrets
              key: replication_user
        - name: REPLICATION_PASSWORD
          valueFrom:
            secretKeyRef:
              name: wrestlingdev-secrets
              key: replication_password
        ports:
        - containerPort: 3306
          name: mariadb
        volumeMounts:
        - name: wrestlingdev-mariadb-persistent-storage
          mountPath: /var/lib/mysql
        - name: mysettings-config-volume
          mountPath: /etc/mysql/mariadb.conf.d
        # lifecycle: create replication user with proper privileges if it doesn't exist
        lifecycle:
          postStart:
            exec:
              command:
              - sh
              - -c
              - |
                # Wait up to 60s for mysqld to be available
                for i in $(seq 1 60); do
                  if mysqladmin ping -uroot -p"$MARIADB_ROOT_PASSWORD" --silent; then
                    echo "mysqld is up"
                    break
                  fi
                  sleep 1
                done

                echo "Ensuring replication user ${REPLICATION_USER} exists and has REPLICATION SLAVE privileges"

                # Create the replication user if it doesn't exist and grant replication privileges.
                # Use CREATE USER IF NOT EXISTS so the command is idempotent.
                mysql -uroot -p"$MARIADB_ROOT_PASSWORD" -e "CREATE USER IF NOT EXISTS '${REPLICATION_USER}'@'%' IDENTIFIED BY '${REPLICATION_PASSWORD}';" 2>/dev/null || true
                mysql -uroot -p"$MARIADB_ROOT_PASSWORD" -e "GRANT REPLICATION SLAVE ON *.* TO '${REPLICATION_USER}'@'%';" 2>/dev/null || true
                mysql -uroot -p"$MARIADB_ROOT_PASSWORD" -e "FLUSH PRIVILEGES;" 2>/dev/null || true
                echo "Replication user ready (errors ignored to avoid blocking startup)"
        # resources:
        #   limits:
        #     memory: "512Mi"
        #   requests:
        #     memory: "256Mi"
      - image: jcwimer/mariadb-rclone-backup-docker:10.3
        name: mariadb-backup
        env:
        - name: DB_PASSWORD
          valueFrom:
           secretKeyRef:
             name: wrestlingdev-secrets
             key: dbpassword
        - name: CRON_SCHEDULE
          value: "*/5 * * * *"  # every 5 minutes
        - name: DB_USERNAME
          valueFrom:
           secretKeyRef:
             name: wrestlingdev-secrets
             key: dbusername
        - name: DB_HOST
          value: "127.0.0.1"
        - name: DAYS_TO_KEEP
          value: "7"
        - name: RCLONE_TYPE
          valueFrom:
           secretKeyRef:
             name: wrestlingdev-secrets
             key: rclone_type
        - name: S3_ACCESS_ID
          valueFrom:
           secretKeyRef:
             name: wrestlingdev-secrets
             key: s3_access_id
        - name: S3_ACCESS_KEY
          valueFrom:
           secretKeyRef:
             name: wrestlingdev-secrets
             key: s3_access_key
        - name: S3_ENDPOINT
          valueFrom:
           secretKeyRef:
             name: wrestlingdev-secrets
             key: s3_endpoint
        - name: S3_REGION
          valueFrom:
           secretKeyRef:
             name: wrestlingdev-secrets
             key: s3_region
        - name: RCLONE_EXTRA_ARGS
          valueFrom:
           secretKeyRef:
             name: wrestlingdev-secrets
             key: rclone_extra_args
        - name: RCLONE_PATH
          valueFrom:
           secretKeyRef:
             name: wrestlingdev-secrets
             key: rclone_path
        volumeMounts:
        - name: wrestlingdev-mariadb-persistent-storage
          mountPath: /var/lib/mysql
        - name: mysettings-config-volume
          mountPath: /etc/mysql/mariadb.conf.d
        # resources:
        #   limits:
        #     memory: "100Mi"
        #   requests:
        #     memory: "50Mi"
        #     cpu: "0.1"
      - image: prom/mysqld-exporter:v0.11.0
        name: mariadb-exporter
        ports:
        - containerPort: 9125
          name: "http"
        args:
        - --web.listen-address=0.0.0.0:9125
        - --web.telemetry-path=/metrics
        - --collect.heartbeat
        - --collect.heartbeat.database=sys_operator
        env:
        - name: DB_PASSWORD
          valueFrom:
           secretKeyRef:
             name: wrestlingdev-secrets
             key: dbpassword
        - name: DB_USERNAME
          valueFrom:
           secretKeyRef:
             name: wrestlingdev-secrets
             key: dbusername
        - name: DB_HOST
          value: "127.0.0.1:3306"
        - name: DATA_SOURCE_NAME
          value: $(DB_USERNAME):$(DB_PASSWORD)@($(DB_HOST))/
        - name: DAYS_TO_KEEP
          value: "7"
        # resources:
        #   limits:
        #     memory: "128Mi"
        #   requests:
        #     memory: "32Mi"
        #     cpu: "10m"
        livenessProbe:
          httpGet:
            path: /metrics
            port: 9125
          initialDelaySeconds: 30
          periodSeconds: 30
          timeoutSeconds: 30
      volumes:
      - name: wrestlingdev-mariadb-persistent-storage
        persistentVolumeClaim:
          claimName: wrestlingdev-mariadb-pv-claim
      - name: mysettings-config-volume
        configMap:
          name: mariadb-mysettings
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: mariadb-mysettings
  labels:
    kubernetes.io/cluster-service: "true"
    addonmanager.kubernetes.io/mode: EnsureExists
data:
  70-mysettings.cnf: |
    [mariadb]
    # Slow log
    slow_query_log=1
    #slow_query_log_file=/var/log/mariadb/slow.log
    slow_query_log_file=/var/lib/mysql/slow.log
    long_query_time=0.2
    # mysqltunner recommendations
    tmp_table_size=32M
    max_heap_table_size=32M
    performance_schema=ON
    innodb_log_file_size=32M
    table_open_cache=4000
    expire_logs_days=7
    
    # /etc/mysql/mariadb.conf.d/70-mysettings.cnf
