#!/usr/bin/env python3

import pathlib
import re
import sys


tuxmake = (pathlib.Path(__file__).parent / "../..").resolve()
sys.path.insert(0, str(tuxmake))


from tuxmake.runtime import DockerRuntime


HEADER = """
# DO NOT EDIT MANUALLY; THIS FILE IS AUTOGENERATED by the `gen-gitlab-ci`
# script. Rerun the script to update this file, and commit it to version
# control.

stages:
    - build-base
    - publish-base
    - build
    - publish

.docker:
    image: docker:19.03.11-dind
    services:
        - name: docker:19.03.11-dind
    variables:
        DOCKER_DRIVER: overlay2
    before_script:
        - apk add make python3
        - cd support/docker/
        - ./configure
        - 'docker login --username="${DOCKER_USERNAME}" --password-stdin < "${DOCKER_PASSWORD_FILE}"'
"""

PUBLISH_JOB = """
docker-images-{group}-{host}:
    stage: {stage}
    extends: .docker
    variables:
        TAG: "-{host}"
    script:
        - "make publish-{group}"
    tags: [{tag}]
    needs: {needs}
    rules:
        - if: '$CI_PIPELINE_SOURCE == "schedule" && $TUXMAKE_DOCKER_IMAGES == "{rebuild}"'
"""

PUBLISH_MULTIARCH_JOB = """
docker-images-{group}-multiarch:
    stage: {stage}
    extends: .docker
    variables:
        DOCKER_CLI_EXPERIMENTAL: "enabled"
        ARCH_TAGS: "{arch_tags}"
    script:
        - "make publish-multiarch-{group}"
    needs: {needs}
    rules:
        - if: '$CI_PIPELINE_SOURCE == "schedule" && $TUXMAKE_DOCKER_IMAGES == "{rebuild}"'
"""


runtime = DockerRuntime()
groups = sorted(
    set(
        [
            (re.sub(r"-", "_", i.group), i.rebuild)
            for i in runtime.images
            if i.group != "ci"
        ]
    )
)
hosts = set()
for img in runtime.images:
    for host in img.hosts:
        hosts.add(host)
hosts = sorted(hosts)

print(HEADER)

arch_tags = " ".join([f"-{h}" for h in hosts])
for group, rebuild in groups:
    for host in hosts:
        if group == "base" or rebuild == "daily":
            needs = "[]"
        else:
            needs = "['docker-images-base-multiarch']"
        if host == "arm64":
            tag = "arm64-dind"
        else:
            tag = ""
        if group == "base":
            stage = "build-base"
        else:
            stage = "build"
        print(
            PUBLISH_JOB.format(
                group=group,
                host=host,
                tag=tag,
                needs=needs,
                rebuild=rebuild,
                stage=stage,
            )
        )

    if group == "base":
        stage = "publish-base"
    else:
        stage = "publish"
    print(
        PUBLISH_MULTIARCH_JOB.format(
            group=group,
            arch_tags=arch_tags,
            needs=repr([f"docker-images-{group}-{host}" for host in hosts]),
            rebuild=rebuild,
            stage=stage,
        )
    )
