import argparse
import logging
import os
import sys
import yaml


def yaml_files(directory):
    for file in os.listdir(directory):
        path = os.path.join(directory, file)
        if os.path.isfile(path):
            yield path


def main():
    logging.basicConfig(level=logging.INFO)

    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument("dir", help="directory containing manifests")
    args = arg_parser.parse_args()

    if not os.path.isdir(args.dir):
        logging.error('"%s" is not a directory', args.dir)
        sys.exit(2)

    for path in yaml_files(args.dir):
        logging.info("Filtering file: %s", path)
        with open(path, 'r') as f:
            yaml_str = f.read()

        try:
            filtered = list(yaml.safe_load_all(yaml_str))
        except Exception as err:
            logging.warning("Error parsing file %s:\n%s", path, err)
            continue

        logging.info("Modify template namespace")
        for template in filtered:
            for parameter in template["parameters"]:
                if parameter["name"] == "SRC_PVC_NAMESPACE":
                    parameter["value"] = "openshift-virtualization-os-images"

        with open(path, 'w') as f:
            yaml.safe_dump_all(filtered, f, default_flow_style=False)


if __name__ == '__main__':
    main()