#!/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_GIT_REF = "v1.28.0"
MANIFESTS = set(
    [
        "cinder-csi-controllerplugin-rbac.yaml",
        "cinder-csi-controllerplugin.yaml",
        "cinder-csi-nodeplugin-rbac.yaml",
        "cinder-csi-nodeplugin.yaml",
        "csi-cinder-driver.yaml",
    ]
)


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

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

    # NOTE(mnaser): CAPI does not like "List" type resources, so we refactor
    #               them to be a list of YAML documents.
    for doc in yaml.safe_load_all(r.text):
        if doc["kind"] == "Deployment":
            doc["spec"]["template"]["spec"]["tolerations"] = [
                {
                    "effect": "NoSchedule",
                    "key": "node-role.kubernetes.io/master",
                },
                {
                    "effect": "NoSchedule",
                    "key": "node-role.kubernetes.io/control-plane",
                },
            ]

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

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