---
stages:
  - tox
  - documentation
  - sonarqube
  - trigger_jenkins_build
  - publish-prod-1
  - publish-prod-2

####################################  tox   -   Testing and linting
run-tox-pipeline:
  stage: tox
  tags:
    - docker-executor
  image: python:3.12

  services:
    - postgres:14

  # Change pip's cache directory to be inside the project directory since we can
  # only cache local items.
  variables:
    POSTGRES_DB: gso-test-db
    POSTGRES_USER: nwa
    POSTGRES_PASSWORD: nwa
    DATABASE_HOST: "postgres"
    PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"

  cache:
    key: tox-virtualenv
    paths:
      - .cache/pip
      - venv/

  before_script:
    - pip install virtualenv
    - virtualenv venv
    - . venv/bin/activate
    - pip install tox

  script:
    - tox

  artifacts:
    paths:
      - htmlcov

##### MkDocs  - Generate documentation
build-documentation:
  stage: documentation
  tags:
    - docker-executor
  image: python:latest

  before_script:
    - cd $CI_PROJECT_DIR/docs
  script:
    - build-docs.sh

  artifacts:
    paths:
      - public

##### Vale    - Documentation linter
lint-documentation:
  stage: documentation
  image:
    name: jdkato/vale:latest
    entrypoint: [""]

  tags:
    - docker-executor
  needs:
    - job: build-documentation # Only run when documentation has been built
      artifacts: true

  before_script:
    - cd $CI_PROJECT_DIR/docs/vale
    - vale sync

  script:
    - vale --glob='!*/migrations/*' $CI_PROJECT_DIR/docs/ $CI_PROJECT_DIR/gso/

##### Publish documentation artefacts
publish-prod-2:
  stage: publish-prod-2
  # First deploy to prod-2
  tags:
    - gap-docs-prod-2

  only:
    refs:
      - main  # Only publish when on the main branch
  needs:
    - job: build-documentation
      artifacts: true

  script:
    - rm -rf /var/www/gap-docs/*
    - mv $CI_PROJECT_DIR/public/* /var/www/gap-docs/

publish-prod-1:
  stage: publish-prod-1
  # When successful, also deploy to prod-1
  tags:
    - gap-docs-prod-1

  only:
    refs:
      - main  # Only publish when on the main branch

  needs:
    - job: build-documentation
      artifacts: true

  script:
    - rm -rf /var/www/gap-docs/*
    - mv $CI_PROJECT_DIR/public/* /var/www/gap-docs/

sonarqube:
  stage: sonarqube
  image: sonarsource/sonar-scanner-cli:10.0
  script:
    - sonar-scanner -Dsonar.login=$SONAR_TOKEN -Dproject.settings=./sonar.properties
  tags:
    - docker-executor

trigger_jenkins_build:
  stage: trigger_jenkins_build
  image: alpine:latest
  before_script:
    - apk add --no-cache curl
  script: curl -u "$JENKINS_USERNAME:$JENKINS_API_TOKEN"
    --data "PROJECT=geant-service-orchestrator"
    "http://test-swd-release-service01.geant.org:8080/job/build-python-snapshot/buildWithParameters"
  only:
    - develop
  tags:
    - docker-executor