default:
  before_script:
    - set -e
    # env -0 | sort -z | tr '\0' '\n': Sort env output alphabetically, keeping multiline variables intact
    # egrep: Remove sensitive information from the output of env
    #- env -0 | sort -z | tr '\0' '\n' | egrep -ve '^(DOCKER_AUTH_CONFIG|GOOGLE_APPLICATION_CREDENTIALS)=.*'
  interruptible: true
  tags:
    - 1cpu-4gb

stages:
  - install_test
  - deploy
  - deploy_production

install_test:
  stage: install_test
  image: "europe-north1-docker.pkg.dev/holi-shared/docker-hub-remote/python:3.13-slim"
  script:
    - pip install -r requirements.txt
    - pip install -r dev-requirements.txt
    - pytest
  interruptible: true

.deploy:
  stage: "deploy"
  image:
    name: "europe-north1-docker.pkg.dev/holi-shared/docker-hub-remote/hashicorp/terraform:1.10.5"
    # default entrypoint is terraform command, but we want to run shell scripts
    entrypoint: ["/bin/sh", "-c"]
  artifacts:
    paths:
      - 'terraform/environments/crash.log' # optional, only available in case of a crash/panic
      - 'terraform/environments/terraform-*.log' # separate log for every step/command
    name: '${CI_JOB_NAME}_${CI_JOB_ID}'
    #when: on_failure # can't do that for api base url, but can't define multiple artifacts
    expire_in: 1 week
  variables:
    ENVIRONMENT_ID: $CI_ENVIRONMENT_SLUG
  script:
    - apk add zip
    - zip -r search_integration.zip requirements.txt *.py
    - terraform/environments/scripts/create-or-update-env.sh "$ENVIRONMENT_ID" "$CI_COMMIT_SHA"
  interruptible: false

staging_deploy:
  extends: .deploy
  variables:
    ENVIRONMENT_ID: 'staging'
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
      when: on_success
  resource_group: staging

production_deploy:
  extends: .deploy
  stage: "deploy_production"
  needs: ["staging_deploy"]
  variables:
    ENVIRONMENT_ID: 'production'
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
      when: on_success
  resource_group: production