"""
Update the version of every pom.xml, for a given program, at a given location

usage: set_pom_version.py [-h] [-n PROGRAM_NAME] [-p PATH] version

Set every pom.xml for program_name to given version

positional arguments:
  version

optional arguments:
  -h, --help            show this help message and exit
  -n PROGRAM_NAME, --name PROGRAM_NAME
  -p PATH, --path PATH


Example:
    python set_pom_version.py 0.14-SNAPSHOT --name simstadt --path /path/to/simstadt/
"""
import argparse
from pathlib import Path
import xmltodict


PROGRAM_NAME = 'simstadt'
SCRIPT_DIR = Path(__file__).resolve().parent


def set_version(program_name: str, parent_path: Path, version: str):
    print(f"Setting Version to {version}, for {program_name}, in {parent_path}")
    pom_paths = parent_path.glob(f'{program_name}*/**/pom.xml')
    irrelevant_pom_paths = parent_path.glob(f'{program_name}*/**/target/pom.xml')

    pom_paths = sorted(set(pom_paths) - set(irrelevant_pom_paths))

    for pom_path in pom_paths:
        print(pom_path, end='')
        with open(pom_path, "r") as pom_content:
            xml_string = pom_content.read()
            data = xmltodict.parse(xml_string)

        project_info = data["project"]
        if "version" in project_info:
            project_info["version"] = version
        if "parent" in project_info:
            project_info["parent"]["version"] = version
        xml_string = xmltodict.unparse(data, pretty=True)

        with open(pom_path, "w") as pom_content:
            pom_content.write(str(xml_string))

        print(" ✔")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description='Set every pom.xml for program_name to given version'
    )

    parser.add_argument('version', type=str)
    parser.add_argument('-n', '--name', default=PROGRAM_NAME,
                        metavar='PROGRAM_NAME', type=str)
    parser.add_argument('-p', '--path', default=SCRIPT_DIR, type=Path)
    args = parser.parse_args()

    set_version(args.name, args.path, args.version)
