#!/usr/bin/env python3

# Copyright (c) 2023 VEXXHOST, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

# This script is used to sync the CCM manifests from the CCM repo to the
# manifests folder.

import requests
import yaml

MANIFESTS = set(
    [
        "csi-controllerplugin-rbac.yaml",
        "csi-controllerplugin.yaml",
        "csi-nodeplugin-rbac.yaml",
        "csi-nodeplugin.yaml",
        "csidriver.yaml",
    ]
)


def set_namespace(doc, namespace="kube-system"):
    cluster_scope_kinds = [
        "ClusterRole",
        "ClusterRoleBinding",
        "CSIDriver",
        "List",
    ]
    binding_kinds = [
        "ClusterRoleBinding",
        "RoleBinding",
    ]
    if doc["kind"] not in cluster_scope_kinds:
        doc["metadata"]["namespace"] = namespace

    if doc["kind"] in binding_kinds:
        for item in doc["subjects"]:
            item["namespace"] = namespace
    return doc


for manifest in MANIFESTS:
    url = f"https://raw.githubusercontent.com/kubernetes/cloud-provider-openstack/master/manifests/manila-csi-plugin/{manifest}"  # noqa E501

    docs = []
    r = requests.get(url)

    for doc in yaml.safe_load_all(r.text):
        if doc["kind"] == "StatefulSet":
            doc["spec"]["template"]["spec"]["containers"][3]["env"][3][
                "value"
            ] = "unix:///var/lib/kubelet/plugins/csi-nfsplugin/csi.sock"
            doc["spec"]["template"]["spec"]["containers"][3]["env"][4]["value"] = "NFS"
            doc["spec"]["template"]["spec"]["containers"][3]["image"] = "registry.k8s.io/provider-os/manila-csi-plugin:latest"
            doc["spec"]["template"]["spec"]["containers"][3]["volumeMounts"][1]["mountPath"] = "/var/lib/kubelet/plugins/csi-nfsplugin"
            doc["spec"]["template"]["spec"]["volumes"][1]["hostPath"]["path"] = "/var/lib/kubelet/plugins/csi-nfsplugin"


        if doc["kind"] == "DaemonSet":
            doc["spec"]["template"]["spec"]["containers"][1]["env"][3][
                "value"
            ] = "unix:///var/lib/kubelet/plugins/csi-nfsplugin/csi.sock"
            doc["spec"]["template"]["spec"]["containers"][1]["env"][4]["value"] = "NFS"
            doc["spec"]["template"]["spec"]["containers"][1]["image"] = "registry.k8s.io/provider-os/manila-csi-plugin:latest"
            # Set FWD plugin
            doc["spec"]["template"]["spec"]["containers"][1]["volumeMounts"][1]["mountPath"] = "/var/lib/kubelet/plugins/csi-nfsplugin"
            doc["spec"]["template"]["spec"]["volumes"][2]["hostPath"]["path"] = "/var/lib/kubelet/plugins/csi-nfsplugin"
            # Set toleration
            doc["spec"]["template"]["spec"]["tolerations"] = [{"operator": "Exists"}]

        if doc["kind"] == "List":
            for item in doc["items"]:
                docs.append(set_namespace(item))
        else:
            docs.append(set_namespace(doc))

    with open(f"magnum_cluster_api/manifests/manila-csi/{manifest}", "w") as fd:
        yaml.dump_all(docs, fd, default_flow_style=False)
