#   Copyright 2022 Google Inc. All Rights Reserved.
#
#  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.

logsBucket: "gs://${PROJECT_ID}_gcblogs"

steps:
- name: 'node:19'
  id: npm-install
  entrypoint: 'npm'
  args: ['--prefix', 'web/', 'install']

- name: 'node:19'
  id: npm-build
  entrypoint: 'npm'
  args: ['--prefix', 'web/', 'run', 'build']

# prefetch the ko builder image
- name: gcr.io/$PROJECT_ID/ko
  id: ko-prefetch
  entrypoint: /bin/sh
  args:
    - -c 
    - |
      /ko version
  waitFor: ['-']

- name: gcr.io/$PROJECT_ID/ko
  id: ko-build
  entrypoint: /bin/sh
  env:
    - 'KO_DOCKER_REPO=gcr.io/$PROJECT_ID'
  # write the newly created container image path to a file for use in another step
  args:
    - -c
    - |
      echo $(/ko publish ./cmd/ping --tags pr-$_PR_NUMBER,pr-$_PR_NUMBER-$SHORT_SHA) > ./image.txt || exit 1

# prefetch the cloud-sdk builder
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
  id: cloud-sdk-prefetch
  args: ['gcloud', '--version'] 
  waitFor: ['-']

- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
  id: run-deploy-image
  entrypoint: /bin/bash
  args:
    - -c
    - |
      gcloud run deploy pr-${_PR_NUMBER}-us-central1 \
      --description="Iowa (pr-${_PR_NUMBER})" \
      --image=$(cat ./image.txt) \
      --region=us-central1 \
      --labels="env=pr-${_PR_NUMBER}"

- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
  id: run-iam-allUsers
  entrypoint: /bin/bash
  args:
    - -c
    - |
      gcloud run services add-iam-policy-binding pr-${_PR_NUMBER}-us-central1 \
      --member="allUsers" \
      --role="roles/run.invoker" \
      --region=us-central1
 
- name: 'hashicorp/terraform:1.10'
  id: terraform-init
  args: ['-chdir=tools/terraform', 'init', '-reconfigure']
  waitFor: ['-']

- name: 'hashicorp/terraform:1.10'
  id: terraform-plan-preview
  entrypoint: /bin/sh
  args:
    - -c
    - |
      terraform -chdir=tools/terraform plan \
      -var image=$(cat ./image.txt)
