#  Preconditions for this CICD script:
# Self-hosted GitLab with GitLab shell-based runner set up on Amazon Linux 2
# We installed pyenv & Python 3.10.5 via pyenv on the runner machine
# for the gitlab-runner user

# If the self-hosted runner uses the Docker executor, the script will look differently,
# e.g. starting with: image: python:3.10
# see details https://docs.gitlab.com/runner/

# Add default tags for all jobs
default:
  tags:
    - prod01-data01  # tag for the GitLab runner the client has setup for us

# Environment variables for Snowflake permissions
variables:
  PERMISSION_BOT_DATABASE: "PERMIFROST"
  PERMISSION_BOT_USER: "PERMIFROST"
  PERMISSION_BOT_ROLE: "SECURITYADMIN"
  PERMISSION_BOT_WAREHOUSE: "ADMIN"
  PERMISSION_BOT_ACCOUNT: $SNOWFLAKE_ACCOUNT

# Pipeline stages in order of execution
stages:
  - dry-run
  - deploy

# use before script to ensure that setup commands are executed before each job
before_script:
  - |
    # Setup Snowflake private key
    echo "$PERMISSION_BOT_PRIVATE_KEY_ENCODED_BASE64" | \
      base64 --decode > $HOME/snowflake_permifrost.p8
    chmod 600 $HOME/snowflake_permifrost.p8
    export PERMISSION_BOT_KEY_PATH=$HOME/snowflake_permifrost.p8

  - |
    # Setup Python environment - needs to be done due to using self-hosted shell-based runner
    export PYENV_ROOT="/home/gitlab-runner/.pyenv"
    export PATH="$PYENV_ROOT/bin:$PATH"
    eval "$(pyenv init -)"
    pyenv shell 3.10.5
    python --version
    pip install --upgrade pip
    pip install -r requirements.txt

# Job to test changes without applying them on merge requests
dry-run-job:
  stage: dry-run
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        - permifrost.yml
  script:
    - tundri run --filepath permifrost.yml --dry

# Job to apply changes to Snowflake on main branch (after merging)
deploy-job:
  stage: deploy
  rules:
    # Only deploy on main branch when permifrost.yml changes
    - if: $CI_COMMIT_BRANCH == "main"
      changes:
        - permifrost.yml
  script:
    - tundri run --filepath permifrost.yml
