pypi_to_docker_missing_version:
    stage: build
    image: alpine:latest
    variables:
        IMAGE_NAME: ""
        PACKAGE_INDEX_API_URL: https://pypi.org/pypi
        PACKAGE_NAME: $CI_PROJECT_NAME
        REPOSITORIES_API_URL: https://registry.hub.docker.com/v2/repositories
        SORT_CMD: sort -V
        TAGS: ""
    script:
        #!/bin/bash
        - apk update
        - apk add --no-cache curl jq

        # get docker tags
        - echo "Image name=$IMAGE_NAME"
        - docker_url="$REPOSITORIES_API_URL/$IMAGE_NAME/tags"

        # get all tags
        - while [ -n "$docker_url" ]; do
        - docker_response=$(curl -s "$docker_url")
        - if [ "$(echo "$docker_response" | jq -r '.results | length')" -eq 0 ]; then
        - break
        - fi
        - TAGS="$TAGS $(echo "$docker_response" | jq -r '.results[].name')"
        - docker_url=$(echo "$docker_response" | jq -r '.next')
        - if [ "$docker_url" = "null" ]; then
        - docker_url=""
        - fi
        - done
        - echo "tags on docker=$TAGS"

        # pypi
        - pypi_url="$PACKAGE_INDEX_API_URL/$PACKAGE_NAME/json"
        - pypi_response=$(curl -s "$pypi_url")
        - releases=$(echo "$pypi_response" | jq -r '.releases | keys[]')

        - echo "releases on pypi:"
        - printf "%s " $releases

        # find missing releases
        - missing_releases=""
        - eval 'for release in $releases; do found=0; for tag in $TAGS; do if [ "$release" = "$tag" ]; then found=1; break; fi; done; if [ $found -eq 0 ]; then missing_releases="$missing_releases $release"; fi; done'
        - missing_releases=$(echo $missing_releases)
        - echo "missing tags=$missing_releases"

        # regex pattern for versioning (adjust if needed)
        # sorted_releases=$(printf "%s\n" $missing_releases | grep -E "$regex" | sort -t. -k1,1n -k2,2n -k3,3n)
        # templated version is simpler
        - sorted_releases=$(printf "%s\n" $missing_releases | $SORT_CMD)

        # print the sorted versions
        - echo "Sorted releases:"
        - printf "%s " $sorted_releases

        - version_to_publish=$(echo $sorted_releases | awk '{print $1}')
        - 'echo "Version to publish: $version_to_publish"'

        - echo "$version_to_publish" > version.txt
        - cat version.txt
    artifacts:
        name: "version"
        paths:
            - version.txt
        expire_in: 1 day