#!/usr/bin/python3

import yaml
import sys

def get_chart_version(chart_name: str) -> str:
    with open(f"./{chart_name}-chart/Chart.yaml") as f:
        chart = yaml.safe_load(f)
        return chart["version"]

def get_charts(chart):
    if not chart["chart"].startswith("%%CHART_REPO%%"):
        # Not a locally managed chart
        return {}

    chart_name = chart["chart"][len("%%CHART_REPO%%/%%CHART_PREFIX%%"):]
    charts = { chart_name: chart["version"] }
    for child_chart in chart.get("dependencyCharts", []) + chart.get("addonCharts", []):
        charts.update(get_charts(child_chart))
    return charts

def get_charts_list():
    with open("./release-manifest-image/release_manifest.yaml") as f:
        manifest = yaml.safe_load(f)
    charts = {}
    for chart in manifest["spec"]["components"]["workloads"]["helm"]:
        charts.update(get_charts(chart))
    return charts

def main():
    print("Checking charts versions in release manifest")
    success = True
    charts = get_charts_list()
    for chart in charts:
        expected_version = get_chart_version(chart)
        if expected_version != charts[chart]:
            success = False
            print(f"{chart}: Expected: {expected_version}, Got: {charts[chart]}")
    if not success:
        sys.exit(1)
    else:
        print("All local charts in release manifest are using the right version")

if __name__ == "__main__":
    main()
