# Copyright 2019 Google, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

name: Build and Deploy -- swagger

on:
  push:
    branches:
      - main

env:
  #PROJECT_ID: "${{ secrets.GCP_PROJECT }}"
  #SERVICE_ACCOUNT_EMAIL: "${{ secrets.GCP_SA_EMAIL }}"
  SERVICE_NAME: apim-swagger-editor-cas
  RUN_REGION_EUW4: europe-west4

jobs:
  setup-build-deploy:
    name: Setup, Build, and Deploy
    runs-on: ubuntu-latest
    
    permissions:
      contents: 'read'
      id-token: 'write'

    steps:
      - name: Checkout
        uses: actions/checkout@v2
      # Setup gcloud CLI
      - id: "auth"
        name: "Authenticate to Google Cloud"
        uses: "google-github-actions/auth@v0.4.1"
        with:
          workload_identity_provider: "projects/1093212293405/locations/global/workloadIdentityPools/apim-dev-pool/providers/apim-dev-gcp-provider"
          service_account: "cloud-build-deploy@ingka-apim-global-dev.iam.gserviceaccount.com"
      - id: "gcloud"
        name: "gcloud"
        run: |-
          gcloud auth login --brief --cred-file="${{ steps.auth.outputs.credentials_file_path }}"
      # Build and push image to Google Container Registry
      - name: Build
        run: |-
          gcloud config set project ingka-apim-global-dev
          gcloud builds submit \
            --quiet \
            --tag "gcr.io/ingka-apim-global-dev/$SERVICE_NAME:$GITHUB_SHA" \
            --gcs-log-dir "gs://apim_cloud_build/swagger-cas/log" \
            --gcs-source-staging-dir "gs://apim_cloud_build/swagger-cas/dev"

      # Deploy image to Cloud Run in EU West4
      - name: Deploy service in EU West4
        run: |-
          gcloud run deploy "$SERVICE_NAME" \
            --quiet \
            --region "$RUN_REGION_EUW4" \
            --image "gcr.io/ingka-apim-global-dev/$SERVICE_NAME:$GITHUB_SHA" \
            --platform "managed" \
            --allow-unauthenticated \
            --service-account="workbench-serviceaccount@ingka-apim-global-dev.iam.gserviceaccount.com" \
            --memory 1Gi