import os
import shutil
import sys

# if len(sys.argv) != 2:
#     raise Exception("Push to Docker Hub will not work, please provide username as argument")

DOCKER_COMPOSE_NAME = "Dockerfile"
ROOT = './'
SOURCEPATH = f'{ROOT}src/'
DOCKER_USERNAME = "alexx882"

paths = []
for r, _, f in os.walk(SOURCEPATH):
    for filename in f:
        if DOCKER_COMPOSE_NAME == filename:
            paths.append(os.path.normpath(r))

command_args = [{'path': path,
                 'name': str(path).split(os.path.normpath('/'))[-1]}
                for path
                in paths]

error:int = 0
res_str = []
for command_arg in command_args:
    path = command_arg['path']
    image_name = f"{DOCKER_USERNAME}/{command_arg['name']}"

    # copy Dockerfile into root dir to have access to modules folder
    shutil.copy2(os.path.join(path, DOCKER_COMPOSE_NAME), ROOT)

    # build then remove Dockerfile
    exit_val = os.system(f"docker image build -t {image_name} {ROOT}")
    os.remove(os.path.join(ROOT, DOCKER_COMPOSE_NAME))

    res_str.append(f"{image_name} built with exit code {exit_val}")
    
    if exit_val != 0:
        error = exit_val

    else:
        # push created Docker image
        exit_val = os.system(f"docker push {image_name}")
        
        res_str.append(f"{image_name} pushed with exit code {exit_val}")
        if exit_val != 0:
            error = exit_val


print(f"Found {len(command_args)} images")
for s in res_str:
    print(s)

sys.exit(1 if error > 0 else 0)