apiVersion: batch/v1
kind: Job
metadata:
  name: ghost-db-init
  labels:
    component: db-init
spec:
  template:
    metadata:
      labels:
        component: db-init
    spec:
      containers:
        - name: db-init
          image: {{ .apps.mysql.image }}
          command: ["/bin/bash", "-c"]
          args:
            - |
              mysql -h ${DB_HOSTNAME} -P ${DB_PORT} -u root -p${MYSQL_ROOT_PASSWORD} <<EOF
              CREATE DATABASE IF NOT EXISTS ${DB_DATABASE_NAME};
              CREATE USER IF NOT EXISTS '${DB_USERNAME}'@'%' IDENTIFIED BY '${DB_PASSWORD}';
              GRANT ALL PRIVILEGES ON ${DB_DATABASE_NAME}.* TO '${DB_USERNAME}'@'%';
              FLUSH PRIVILEGES;
              EOF
          env:
            - name: MYSQL_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: mysql-secrets
                  key: apps.mysql.rootPassword
            - name: DB_HOSTNAME
              value: "{{ .apps.ghost.dbHost }}"
            - name: DB_PORT
              value: "{{ .apps.ghost.dbPort }}"
            - name: DB_DATABASE_NAME
              value: "{{ .apps.ghost.dbName }}"
            - name: DB_USERNAME
              value: "{{ .apps.ghost.dbUser }}"
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: ghost-secrets
                  key: apps.ghost.dbPassword
      restartPolicy: OnFailure