stages:
  - deploy_staging
  - deploy_production

variables:
  NAMESPACE: "default"
  REGISTRY_GCP: europe-west1-docker.pkg.dev/ops-shared-e3afff9d/gitlab-pipeline
  RELEASE_NAME: ${APPLICATION_NAME}
  CHART_DIR: helm-chart
  CI_TEMPLATES_GIT_USER: pipeline-git-ro
  CI_TEMPLATES_GIT_PROJECT_URL: gitlab.com/finboot/it-operations/ci-templates.git
  CI_TEMPLATES_GIT_PASSWORD: gphEDJxZScK9cC9qUdE3
  GKE_REGION: europe-west1

.deployment_script:
  tags:
    - docker
  image:
    name: europe-west1-docker.pkg.dev/ops-shared-e3afff9d/sync-images/finboot-custom/gitlab-job-deploy:stable
  before_script:
    - mkdir -p /etc/deploy
    - echo ${SA_GKE} | base64 -d | base64 -d > /etc/deploy/sa.json
    - gcloud auth activate-service-account --key-file /etc/deploy/sa.json --project=${GKE_PROJECT}
    - gcloud container clusters get-credentials ${GKE_CLUSTER_NAME} --zone ${GKE_REGION} --project ${GKE_PROJECT}
    - echo $SA_GCR >> .google_credentials.json
    - export GOOGLE_APPLICATION_CREDENTIALS=.google_credentials.json
    - gcloud auth application-default print-access-token | helm registry login -u oauth2accesstoken --password-stdin https://europe-southwest1-docker.pkg.dev
  script:
    - git clone https://${CI_TEMPLATES_GIT_USER}:${CI_TEMPLATES_GIT_PASSWORD}@${CI_TEMPLATES_GIT_PROJECT_URL}
    - cd ci-templates
    - scripts/deploy/deploy-template.sh
  timeout: 10m

.deploy_staging_main:
  extends: .deployment_script
  variables:
    SA_GKE: ${SA_GKE_STAGE}
    GKE_PROJECT: ${STAGE_GKE_PROJECT}
    GKE_CLUSTER_NAME: ${STAGE_GKE_CLUSTER_NAME}
    STACK: stage
  environment:
    name: staging
    url: https://${APPLICATION_NAME}.finboot-test.com
  allow_failure: false # Mandatory be success to continue
  when: manual

.deploy_production_main:
  extends: .deployment_script
  variables:
    SA_GKE: ${SA_GKE_PROD}
    GKE_PROJECT: ${PROD_GKE_PROJECT}
    GKE_CLUSTER_NAME: ${PROD_GKE_CLUSTER_NAME}
    STACK: prod
  environment:
    name: production
    url: https://${APPLICATION_NAME}.finboot.com
  needs: ["deploy_staging"] # It needs staging working
  allow_failure: false # Mandatory be success to continue
  when: manual
  only:
    refs:
      - master
      - main
