# [START cloudrun_rails_cloudbuild]
steps:
  - id: "build image"
    name: "gcr.io/cloud-builders/docker"
    entrypoint: 'bash'
    args: ["-c", "docker build --build-arg MASTER_KEY=$$RAILS_KEY -t ${_IMAGE_NAME} . "]
    secretEnv: ["RAILS_KEY"]

  - id: "push image"
    name: "gcr.io/cloud-builders/docker"
    args: ["push", "${_IMAGE_NAME}"]

  - id: "apply migrations"
    name: "gcr.io/google.com/cloudsdktool/cloud-sdk"
    entrypoint: /bin/bash
    secretEnv: ["RAILS_KEY"]
    args:
      - "-c"
      - |
        gcloud run jobs create migrate-job \
          --region ${_REGION} \
          --image ${_IMAGE_NAME} \
          --set-cloudsql-instances ${_CLOUD_SQL_CONNECTION_NAME} \
          --set-env-vars RAILS_MASTER_KEY=$$RAILS_KEY \
          --command bundle \
          --args exec,rails,db:migrate \
          --execute-now --wait && \
          gcloud run jobs delete  migrate-job --region ${_REGION} -q

options:
  dynamicSubstitutions: true

substitutions:
  _REGION: us-central1
  _SERVICE_NAME: rails-cat-album
  _INSTANCE_NAME: cat-album
  _SECRET_NAME: rails-master-key
  _AR_REPO_NAME: cloud-run-source-deploy
  _IMAGE_NAME: ${_REGION}-docker.pkg.dev/${PROJECT_ID}/${_AR_REPO_NAME}/${_SERVICE_NAME}
  _CLOUD_SQL_CONNECTION_NAME: ${PROJECT_ID}:${_REGION}:${_INSTANCE_NAME}

availableSecrets:
  secretManager:
  - versionName: projects/${PROJECT_ID}/secrets/${_SECRET_NAME}/versions/latest
    env: RAILS_KEY

images:
  - "${_IMAGE_NAME}"
# [END cloudrun_rails_cloudbuild]
