image: docker:23.0.5

variables:
  DOCKER_DRIVER: overlay2
  DOCKER_TLS_CERTDIR: "/certs"
  DOCKER_HOST: tcp://docker:2376
  # Where to publish this build's tagged working container.
  DOCKER_SHA: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
  DOCKER_BRANCH: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME
  DOCKER_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_TAG
  DOCKER_LATEST: $CI_REGISTRY_IMAGE:latest

services:
  - docker:23.0.5-dind

stages:
  - build
  - test
  - release

before_script:
  - docker info
  - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY

build-upload:
  image: python:3.11
  stage: build
  before_script:
    - python -V
    - echo "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/pypi"
  script:
    - pip install build twine flit
    - FLIT_INDEX_URL=${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/pypi flit build
    - TWINE_PASSWORD=${CI_JOB_TOKEN} TWINE_USERNAME=gitlab-ci-token python -m twine upload --repository-url ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/pypi dist/*
  rules:
    - if: $CI_COMMIT_TAG
    - if: $CI_PIPELINE_SOURCE == "push" || $CI_COMMIT_BRANCH == "dev"
      when: manual
      allow_failure: true

.build-upload-pypi:
  image: python:3.11
  stage: build
  before_script:
    - python -V
    - echo "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/pypi"
  script:
    - pip install build twine flit
    - flit build
    - python -m twine upload dist/*
  rules:
    - if: $CI_COMMIT_TAG
    - if: $CI_PIPELINE_SOURCE == "push" || $CI_COMMIT_BRANCH == "dev"
      when: manual
      allow_failure: true

build-docker:
  stage: build
  script:
    - docker pull $DOCKER_BRANCH || true
    - docker build --cache-from $DOCKER_BRANCH -f ./Dockerfile --tag $DOCKER_BRANCH .
    - docker push $DOCKER_BRANCH
  rules:
    - if: $CI_COMMIT_TAG || $CI_COMMIT_BRANCH == "main"
    - if: $CI_PIPELINE_SOURCE == "push" || $CI_COMMIT_BRANCH == "dev"
      when: manual
      allow_failure: true

build-tagged-docker:
  stage: build
  script:
    - docker pull $DOCKER_BRANCH || true
    - docker tag $DOCKER_BRANCH $DOCKER_LATEST
    - docker push $DOCKER_LATEST
    - docker tag $DOCKER_BRANCH $DOCKER_TAG
    - docker push $DOCKER_TAG
  rules:
    - if: $CI_COMMIT_TAG
    - if: $CI_PIPELINE_SOURCE == "push" || $CI_COMMIT_BRANCH == "dev"
      when: manual
      allow_failure: true
