#!/usr/bin/env python3
import argparse
import subprocess
images = []


def initArgsList(parser: argparse.ArgumentParser):

    parser.add_argument("-c", "--clear", help="don't clear outdated images", action="store_true")


def loadImages():

    global images
    proc = subprocess.Popen(["docker", "images"], stdout=subprocess.PIPE)
    lines = proc.stdout.readlines()[1:]
    for line in lines:
        line = line.decode("utf-8").rstrip().split()
        if line[1] != "<none>":
            images.append("{}:{}".format(line[0], line[1]))


def bumpImages():

    global images
    for images in images:
        proc = subprocess.Popen(["docker", "pull", images])
        proc.wait()
        print()


def clearImages():

    outdated_images = []
    proc = subprocess.Popen(["docker", "images"], stdout=subprocess.PIPE)
    lines = proc.stdout.readlines()[1:]
    for line in lines:
        line = line.decode("utf-8").rstrip().split()
        if line[1] == "<none>":
            outdated_images.append(line[2])

    if len(outdated_images) > 0:
        proc = subprocess.Popen(["docker", "rmi"] + outdated_images)
        proc.wait()
    else:
        print("No outdated images")


if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    initArgsList(parser)

    args = parser.parse_args()

    loadImages()
    bumpImages()
    if not args.clear:
        clearImages()
