#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of INGInious. See the LICENSE and the COPYRIGHTS files for
# more information about the licensing of this file.


import re
import docker


def main():
    """ Updates all "stock" images (images beginning with 'ingi/inginious-') """
    INFO = '\033[94m'
    WARNING = '\033[33m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'

    stock_images = []
    try:
        docker_connection = docker.from_env()
        for image in docker_connection.images.list():
            for tag in image.attrs["RepoTags"]:
                if re.match(r"^ingi/inginious-(c-[a-z]+|agent):latest$", tag):
                    stock_images.append(tag)
    except:
        print(FAIL + "Cannot connect to Docker!" + ENDC)
        print(FAIL + "Restart this command after making sure the command `docker info` works" + ENDC)
        return

    if len(stock_images) == 0:
        print(WARNING + "You have no image to update. Do not forget to run `inginious-install`." + ENDC)
    else:
        print(INFO + "Currently installed images:")
        for i in stock_images:
            print(INFO + ("- %s" % i) + ENDC)
        for image in stock_images:
            print(INFO + ("Updating %s" % image) + ENDC)
            docker_connection.images.pull(image)
        print(INFO + "Images update done" + ENDC)

if __name__ == "__main__":
    main()