apiVersion: batch/v1
kind: Job
metadata:
  name: firefly-mysql-init
  labels:
    job: firefly-mysql-init
spec:
  template:
    spec:
      restartPolicy: OnFailure
      imagePullSecrets:
        - name: registry.internal.aleemhaji.com
      initContainers:
        - name: firefly-mysql-init
          image: registry.internal.aleemhaji.com/mysql:5.7.26
          command:
            - sh
            - -cx
            - |
              mysql -h ${MYSQL_HOST} -u root -e " \
                CREATE USER IF NOT EXISTS ${FF_DB_USER}@'10.244.%.%'; \
                SET PASSWORD FOR ${FF_DB_USER}@'10.244.%.%' = PASSWORD('${FF_DB_PASSWORD}'); \
                CREATE DATABASE IF NOT EXISTS ${FF_DB_NAME}; \
                GRANT ALL ON ${FF_DB_NAME}.* TO ${FF_DB_USER}@'10.244.%.%';"
          env:
            - name: MYSQL_PWD
              valueFrom:
                secretKeyRef:
                  name: mysql-secrets
                  key: root_password
            - name: MYSQL_HOST
              value: mysql
            - name: FF_DB_USER
              valueFrom:
                configMapKeyRef:
                  name: firefly-config
                  key: mysql_user
            - name: FF_DB_NAME
              valueFrom:
                configMapKeyRef:
                  name: firefly-config
                  key: mysql_database
            - name: FF_DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: firefly-secrets
                  key: mysql_password
      containers:
        - name: firefly-app-init
          image: registry.internal.aleemhaji.com/firefly-iii:5.5.13
          command:
            - sh
            - -c
            - |
              php artisan migrate && \
              php artisan firefly:upgrade-database && \
              php artisan passport:install
          # https://github.com/firefly-iii/firefly-iii/blob/4.7.5.3/.env.docker#L25
          env:
            - name: DB_HOST
              value: mysql
            - name: DB_USERNAME
              valueFrom:
                configMapKeyRef:
                  name: firefly-config
                  key: mysql_user
            - name: DB_DATABASE
              valueFrom:
                configMapKeyRef:
                  name: firefly-config
                  key: mysql_database
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: firefly-secrets
                  key: mysql_password
            - name: APP_KEY
              valueFrom:
                secretKeyRef:
                  name: firefly-secrets
                  key: app_key
