apiVersion: batch/v1
kind: Job
metadata:
  name: keila-db-init
spec:
  template:
    metadata:
      labels:
        component: db-init
    spec:
      restartPolicy: OnFailure
      securityContext:
        runAsNonRoot: true
        runAsUser: 999
        runAsGroup: 999
        seccompProfile:
          type: RuntimeDefault
      containers:
      - name: postgres-init
        image: postgres:15
        securityContext:
          allowPrivilegeEscalation: false
          capabilities:
            drop:
            - ALL
          readOnlyRootFilesystem: false
        env:
        - name: PGHOST
          value: {{ .apps.keila.dbHostname }}
        - name: PGUSER
          value: postgres
        - name: PGPASSWORD
          valueFrom:
            secretKeyRef:
              name: keila-secrets
              key: apps.postgres.password
        - name: DB_NAME
          value: {{ .apps.keila.dbName }}
        - name: DB_USER
          value: {{ .apps.keila.dbUsername }}
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: keila-secrets
              key: apps.keila.dbPassword
        command:
        - /bin/bash
        - -c
        - |
          set -e
          echo "Waiting for PostgreSQL to be ready..."
          until pg_isready; do
            echo "PostgreSQL is not ready - sleeping"
            sleep 2
          done
          echo "PostgreSQL is ready"
          
          echo "Creating database and user for Keila..."
          psql -c "CREATE DATABASE ${DB_NAME};" || echo "Database ${DB_NAME} already exists"
          psql -c "CREATE USER ${DB_USER} WITH PASSWORD '${DB_PASSWORD}';" || echo "User ${DB_USER} already exists"
          psql -c "GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${DB_USER};"
          psql -d ${DB_NAME} -c "GRANT ALL ON SCHEMA public TO ${DB_USER};"
          echo "Database initialization complete"