#!/usr/bin/env python3

import docker
import logging
from time import sleep
from sh import systemctl

SERVICE = 'docker-compose@gitlab.service'

REPOSITORY = 'gitlab/gitlab-ce'
EXTENSION = '-ce.0'
CONTAINER_NAME = 'gitlab'
IMAGE_TAG= f"{REPOSITORY}:migrate"
TAGS = (
    '11.10.4',
    '11.10.8',
    '11.11.8',
    '12.0.12',
    '12.1.17',
    '12.2.12',
    '12.3.9',
    '12.4.8',
    '12.5.10',
    '12.6.8',
    '12.7.8',
    '12.8.8',
    '12.9.1',
)


logging.basicConfig(level=logging.INFO)


def full_tag(tag):
    return f"{REPOSITORY}:{tag}{EXTENSION}"


def get_image_names(container):
    tags = iter(TAGS)
    while True:
        tag = next(tags)
        if full_tag(tag) in container.image.tags:
            return (full_tag(tag), full_tag(next(tags)))


client = docker.from_env()

current_container = client.containers.get(CONTAINER_NAME)
images = client.images.list(name=REPOSITORY)

from_image, to_image = get_image_names(current_container)

logging.info("Pulling Image: %s", to_image)
client.images.pull(to_image)

systemctl('stop', SERVICE)

logging.info("Tag: Image %s to %s", to_image, IMAGE_TAG)
image = client.images.get(to_image)
image.tag(IMAGE_TAG)

systemctl('start', SERVICE)

sleep(1.0)
logging.info("Waiting for healthy container: %s", CONTAINER_NAME)
waited = 0
while True:
    container = client.containers.get(CONTAINER_NAME)
    status = container.attrs['State']['Health']['Status']
    if status == 'healthy':
        logging.info("Healthy container %s: Please check with browser", CONTAINER_NAME)
        break
    waited += 5
    sleep(5)
    logging.info("Waited: %ss", waited)

logging.info("Removing Image: %s", from_image)
client.images.remove(image=from_image)

