image: python:3.10
default:
  tags:
    - docker

stages:
  - build
  - release
  - deploy

cache:
  paths:
    - .venv
    - dist

variables:
  PACKAGE_REGISTRY_URL: ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/pypi
  WHEEL_NAME: 'updates_notifier-${CI_COMMIT_TAG}-py3-none-any.whl'

build-package:
  before_script:
    - pip install -U pip
    - pip install poetry
    - poetry --version
    # forces poetry to create the virtualenv inside project directory
    - poetry config virtualenvs.in-project true
    - poetry check
    - poetry install -vv
  stage: build
  script:
    - poetry build
  artifacts:
    paths:
      - dist/*.whl
    expire_in: 1 week

publish-package:
  before_script:
    - pip install -U pip
    - pip install poetry
    - poetry --version
    # forces poetry to create the virtualenv inside project directory
    - poetry config virtualenvs.in-project true
    - poetry config repositories.gitlab ${PACKAGE_REGISTRY_URL}
    - poetry check
    - poetry install -vv
  stage: release
  rules:
    - if: '$CI_COMMIT_TAG'
  script:
    - poetry publish -r gitlab -u gitlab-ci-token -p ${CI_JOB_TOKEN}

create-release:
  image: registry.gitlab.com/gitlab-org/release-cli:latest
  stage: release
  rules:
    - if: '$CI_COMMIT_TAG'
  script:
    - echo "Creating release…"
    - |
      release-cli create --name "updates-notifier $CI_COMMIT_TAG release" \
      --description "Auto-generated release." --tag-name "$CI_COMMIT_TAG" \
      --ref "$CI_COMMIT_TAG" \
      --assets-link "{\"url\":\"${PACKAGE_REGISTRY_URL}/files/$(sha256sum dist/${WHEEL_NAME})/${WHEEL_NAME}\",\"name\":\"${WHEEL_NAME}\", \"link_type\": \"package\"}"

build-publish-image:
  image: docker:19.03.12
  stage: deploy
  rules:
    - if: '$CI_COMMIT_TAG'
  services:
    - docker:19.03.10-dind
  variables:
    IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_TAG
    IMAGE_TAG_LATEST: $CI_REGISTRY_IMAGE:latest
  script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - |
      docker build -t $IMAGE_TAG \
      --build-arg UPDATES_NOTIFIER_VERSION=$CI_COMMIT_TAG \
      -f cmd/Dockerfile  .
    - docker push $IMAGE_TAG
    - docker tag $IMAGE_TAG $IMAGE_TAG_LATEST
    - docker push $IMAGE_TAG_LATEST
  
