# Copyright 2022 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.

steps:

# Cloning repo because the credentials will be cached in gcloud.sh and will avoid authenticating again and again in subsequent steps
- name: 'gcr.io/cloud-builders/git'
  id: 'clone platform-repos'
  entrypoint: /bin/sh
  args: [ '-c', "git clone https://$$GITHUB_USER:$$GITHUB_TOKEN@github.com/$$GITHUB_ORG/${_REPO_NAME}" ]
  secretEnv: ['GITHUB_TOKEN','GITHUB_USER','GITHUB_ORG']


#Initialize apps directory.Lookup app_runtimes_list.txt to find allowed runtimes and add a terraform module for each runtime under apps folder
- name: 'gcr.io/cloud-builders/gcloud'
  id : 'Initialize dir structure'
  entrypoint: 'bash'
  args: [ '-c',"./${_REPO_NAME}/setup/init.sh $$GITHUB_USER ${_REPO_NAME}" ]
  secretEnv: ['GITHUB_TOKEN','GITHUB_USER','GITHUB_ORG']

- name: 'gcr.io/cloud-builders/gcloud'
  id : 'Handling the variables that could be empty'
  entrypoint: 'sh'
  args:
  - '-c'
  - |
    if [ ${_GITHUB_TEAM} ] ; then
       echo ${_GITHUB_TEAM} > /workspace/github_team
    else
       echo "null" > /workspace/github_team
    fi
    if [ ${_FOLDER_ID} ] ; then
       echo ${_FOLDER_ID} > /workspace/folder
    else
       echo "null" > /workspace/folder
    fi


- name: 'gcr.io/cloud-builders/gcloud'
  id: 'create tf file for app, commit it in github repo and push'
  entrypoint: 'bash'
  args: [ '-c',"./${_REPO_NAME}/setup/generateAppTFCode.sh ${_APP_RUNTIME} ${_APP_NAME} ${_INFRA_PROJECT_ID} $$GITHUB_USER ${PROJECT_ID} `cat /workspace/folder` $$GITHUB_ORG ${_REPO_NAME} ${_TRIGGER_TYPE} ${_GITHUB_TEAM} `cat /workspace/github_team` ${_REGION}"  ]
  secretEnv: ['GITHUB_TOKEN','GITHUB_USER','GITHUB_ORG']

availableSecrets:
  secretManager:
  - versionName: projects/YOUR_SECRET_PROJECT_ID/secrets/github-token/versions/latest
    env: GITHUB_TOKEN
  - versionName: projects/YOUR_SECRET_PROJECT_ID/secrets/github-user/versions/latest
    env: GITHUB_USER
  - versionName: projects/YOUR_SECRET_PROJECT_ID/secrets/github-org/versions/latest
    env: GITHUB_ORG