#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import logging
import utilities
import time

def run_docker_service_scale(stack, service, state):
    utilities.run_command(["docker", "service", "scale", stack + "_" + service + "=" + state])

def run_docker_stack_services(stack, service):
    stdout = utilities.run_command_and_get_stdout(["docker", "stack", "services",
                 "--format", "'{{.Replicas}}'",
                 "--filter", "name=" + stack + "_" + service,
                                                   stack])
    return stdout

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Start or stop the Galaxy container for all the stacks")

    parser.add_argument("-s", "--state",
                        type=int,
                        choices=[0,1],
                        help="State to set the Galaxy container in")

    parser.add_argument("-v", "--verbose",
                        help="Increase output verbosity",
                        action="store_true")

    args = parser.parse_args()
    state = args.state

    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)
        logging.debug("Debug mode")
    else:
        logging.basicConfig(level=logging.INFO)

    stacks = utilities.run_docker_stack_ls()

    # Stop the Galaxy services
    for stack in stacks:
        if stack not in ["traefik", "portainer"]:
            run_docker_service_scale(
                stack=stack,
                service="galaxy",
                state=state
            )

    time.sleep(60)

    # Check that the Galaxy services are down
    for stack in stacks:
        if stack not in ["traefik", "portainer"]:
            stdout = run_docker_stack_services(
                stack=stack,
                service="galaxy"
            )
            if stdout != "0/1":
                logging.error("The Galaxy service is not stopped for %s" % stack)