#!/usr/bin/env python3

import sys
import argparse
import ruamel.yaml


DESCRIPTION = """ Separate Istio YAML into separate components.

Separate Istio YAML definitions into four separate components: crds, install
and cluster-local-gateway.
"""


class YAMLEmitterNoVersionDirective(ruamel.yaml.emitter.Emitter):
    """YAML Emitter that doesn't emit the YAML version directive."""

    def write_version_directive(self, version_text):
        """Disable emitting version directive, i.e., %YAML 1.1."""
        pass


class YAML(ruamel.yaml.YAML):
    """Wrapper of the ruamel.yaml.YAML class with our custom settings."""

    def __init__(self, *args, **kwargs):
        super(YAML, self).__init__(*args, **kwargs)
        # XXX: Explicitly set version for producing K8s compatible manifests.
        # https://yaml.readthedocs.io/en/latest/detail.html#document-version-support
        self.version = (1, 1)
        # XXX: Do not emit version directive since tools might fail to
        # parse manifests.
        self.Emitter = YAMLEmitterNoVersionDirective


yaml = YAML()


def parse_args():
    parser = argparse.ArgumentParser(
        description=DESCRIPTION,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("-f", "--manifest-file", type=str, required=True,
                        dest="manifest_file",
                        help="Istio YAML, generated by istioctl.")
    return parser.parse_args()


def main():
    args = parse_args()
    with open(args.manifest_file, "r") as f:
        objects = [obj for obj in list(yaml.load_all(f)) if obj]
    crds, install, cluster_local = [], [], []
    for obj in objects:
        if obj.get("kind") == "CustomResourceDefinition":
            crds.append(obj)
        elif (obj.get("metadata", {}).get("name", "").
              startswith("cluster-local-gateway")):
            cluster_local.append(obj)
        else:
            install.append(obj)

    with open("crd.yaml", "w") as f:
        yaml.dump_all(crds, f)
    with open("install.yaml", "w") as f:
        yaml.dump_all(install, f)
    with open("cluster-local-gateway.yaml", "w") as f:
        yaml.dump_all(cluster_local, f)


if __name__ == "__main__":
    sys.exit(main())