#!/usr/bin/python3
import json
import os
import glob
import sys
import re


class CheckResult:
    """Class to track count of issues"""

    def __init__(self):
        self.hints = 0
        self.warnings = 0
        self.errors = 0

    def hint(self, msg):
        print(f"Hint: {msg}")
        self.hints += 1

    def warn(self, msg):
        print(f"Warning: {msg}")
        self.warnings += 1

    def error(self, msg):
        print(f"Error: {msg}")
        self.errors += 1


TAG_RE = re.compile(r"(.*\/)?([^:]+):([^:]+)")


def check_tags(helminfo, result):
    release_tag_found = False
    version_tag_found = False
    for tag in helminfo["tags"]:
        (tag_prefix, tag_name, tag_version) = TAG_RE.fullmatch(tag).groups()
        if tag_name != helminfo.get("name"):
            result.warn(
                f"Tag ({tag}) doesn't use the chart name ({helminfo.get('name')})"
            )
        if "release" in helminfo and helminfo["release"] in tag_version:
            release_tag_found = True
        if tag_version.replace("_", "+") == helminfo["version"]:
            version_tag_found = True
    if not release_tag_found:
        result.error(
            "None of the tags are unique to a specific build of the image.\n"
            + "Make sure that at least one tag contains the release."
        )
    if not version_tag_found:
        result.error(
            "None of the tags is the equivalent of the chart's version.\n"
            + "Make sure that one of the tag is the chart version."
        )


def helminfos():
    """Return a list of .helminfo files to check."""
    if "BUILD_ROOT" not in os.environ:
        # Not running in an OBS build container
        return glob.glob("*.helminfo")

    # Running in an OBS build container
    buildroot = os.environ["BUILD_ROOT"]
    topdir = "/usr/src/packages"
    if os.path.isdir(buildroot + "/.build.packages"):
        topdir = "/.build.packages"
    if os.path.islink(buildroot + "/.build.packages"):
        topdir = "/" + os.readlink(buildroot + "/.build.packages")

    return glob.glob(f"{buildroot}{topdir}/HELM/*.helminfo")


def main():
    result = CheckResult()
    for helminfo in helminfos():
        print(f"Looking at {helminfo}")
        with open(helminfo, "rb") as cifile:
            ci_dict = json.load(cifile)
            check_tags(ci_dict, result)

    ret = 0
    if result.errors > 0:
        print("Fatal errors found.")
        ret = 1

    sys.exit(ret)


if __name__ == "__main__":
    main()
