import os
import subprocess
import yaml
import argparse

def main():
    parser = argparse.ArgumentParser(prog='podman-tool',
                    description='Utility for managing podman containers',
                    epilog=""" commands: create: create services specified in ptconfig.yml without starting;
                    start: start one specific service or all services at once;
                    stop: stop one specific service or all services at once;
                    shell: run a shell in an existing service;
                    karaf: run a karaf shell in an existing service (only useful for openHAB);
                    down: stop all services and delete their pods""")

    if "REPO" in os.environ:
        repo = os.environ['REPO'] + '/'
        print(f"Your current repository path is {repo}. To change it, change the REPO environment variable.")
    else:
        repo = ''
        print("The tool will use the config file from the directory it is running in. If you want to change this,"
              "set the REPO environment variable.")

    config = repo + 'ptconfig.yml'
    with open(config, 'r') as ptcfg:
        read_config = yaml.safe_load(ptcfg)

    compose_config = repo + "podman-compose.yml"

    services = read_config['services']

    parser.add_argument("command", help="command to run (create, start, stop, shell, karaf, down)")
    parser.add_argument("service", help="name of service if applicable, or leave empty for all services", nargs='?', default='')
    parser.add_argument("-y", action="store_true", help="automatically confirm any queries")
    args = parser.parse_args()

    def create():
        subprocess.run(["rm", "-rf", compose_config])
        invalid_options = ['addons', 'bindings', 'commands']
        with open(config) as oldfile, open(compose_config, 'w') as newfile:
            for line in oldfile:
                if not any(invalid_option in line for invalid_option in invalid_options):
                    newfile.write(line)
        subprocess.run(["podman-compose", "-f", compose_config, "up", "--no-start"])
        for service in list(read_config['services']):
            for index in list(read_config['services'][service]['addons']['bindings']['commands']):
                subprocess.run([index])

    def start():
        start_service = args.service
        if start_service == '':
            start_service = list(services)
            for i in range(len(start_service)):
                subprocess.run(["podman-compose", "start", start_service[i]])
            exit(0)
        else:
            subprocess.run(["podman-compose", "start", start_service])
            exit(0)

    def stop():
        stop_service = args.service
        if stop_service == '':
            if args.y:
                confirm = "y"
            else:
                confirm = input("Stop all services? (y/N): ")
            if confirm.lower() == "y" or confirm.lower() == "yes":
                stop_service = list(services)
                for i in range(len(stop_service)):
                    subprocess.run(["podman-compose", "stop", stop_service[i]])
                exit(0)
            else:
                print("aborting...")
                exit(0)
        else:
            subprocess.run(["podman_compose", "stop", stop_service])
            exit(0)

    def shell():
        subprocess.run(["podman-compose", "exec", args.service, "sh"])

    def karaf():
        subprocess.run(["podman-compose", "exec", args.service, "/openhab/runtime/bin/client"])

    def down():
        if args.y:
            confirm = "y"
        else:
            confirm = input("Stop all services and delete all pods? (y/N): ")
        if confirm.lower() == "y" or confirm.lower() == "yes":
            subprocess.run(["podman-compose", "-f", compose_config, "down"])
            exit(0)
        else:
            print("aborting...")
            exit(0)


    if args.command == "create":
        create()
    elif args.command == "start":
        start()
    elif args.command == "stop":
        stop()
    elif args.command == "shell":
        shell()
    elif args.command == "karaf":
        karaf()
    elif args.command == "down":
        down()



if __name__ == "__main__":
    main()