# A job to deploy the image and just run database migration.
# Note: when there is the cloud sql proxy running also this job will not exit cleaning, so will need to be manually deleted. e.g kubectl delete job db-migration
# If we use internal cloud sql IP or a put the proxy as a service this should be a solution 
# in meantime, as backup we fail this job after 360 seconds, 6 minutes

apiVersion: batch/v1
kind: Job
metadata:
  name: db-migration
spec:
  completions: 1
  backoffLimit: 5
  activeDeadlineSeconds: 360
  template:
    metadata:
      name: db-migration
    spec:
      restartPolicy: Never
      containers:
      - name: db-migration
        # image: localhost:32000/mapwarper_web:latest
        # You can use envsubst to set the image
        # e.g. IMAGE=localhost:32000/mapwarper_web:latest envsubst < file.yaml 
        image: ${IMAGE}
        command: ["bundle", "exec", "rake", "db:migrate"]
        # set variables from config map from mapwarper-app-config.yml
        envFrom:
          - configMapRef:
              name: mapwarper-app-config
        # Set env variables explicity and secrets from mapwarper-secrets.yml
        env:
          - name: DB_USER
            valueFrom:
              secretKeyRef:
                name: mapwarper-secrets
                key: dbusername
          - name: DB_PASSWORD
            valueFrom:
              secretKeyRef:
                name: mapwarper-secrets
                key: dbpassword
          - name: DB_NAME
            valueFrom:
              secretKeyRef:
                name: mapwarper-secrets
                key: dbname
          - name: SECRET_KEY_BASE
            valueFrom:
              secretKeyRef:
                name: mapwarper-secrets
                key: secret-key-base
          # set env manually
          - name: RAILS_ENV
            value: "production"
          - name: RAILS_SERVE_STATIC_FILES
            value: "true"


      # - name: cloudsql-proxy
      #   image: gcr.io/cloudsql-docker/gce-proxy:1.11
      #   env:
      #     - name: DB_INSTANCE
      #       valueFrom:
      #         secretKeyRef:
      #           name: mapwarper-secrets
      #           key:  dbinstance
      #   command: ["/cloud_sql_proxy"]
      #   args: ["-instances=$(DB_INSTANCE)=tcp:5432", "-credential_file=/secrets/cloudsql/secret_cloud_sql.json"]
      #   volumeMounts:
      #     - name: sql-secrets-volume
      #       mountPath: /secrets/cloudsql
      #       readOnly: true

      volumes:
        - name: sql-secrets-volume
          secret:
            secretName: cloudsql-instance-credentials
