#!/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(
    [
        "cloud-controller-manager-roles.yaml",
        "cloud-controller-manager-role-bindings.yaml",
        "openstack-cloud-controller-manager-ds.yaml",
    ]
)


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

    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):
        docs = []

        if doc["kind"] == "DaemonSet":
            # NOTE(mnaser): Use `/etc/kuberentes/cloud.conf` instead of the
            #               default mounted secret.
            doc["spec"]["template"]["spec"]["containers"][0]["volumeMounts"][2][
                "mountPath"
            ] = "/etc/config/cloud.conf"
            doc["spec"]["template"]["spec"]["volumes"][2]["hostPath"] = {
                "type": "File",
                "path": "/etc/kubernetes/cloud.conf",
            }
            del doc["spec"]["template"]["spec"]["volumes"][2]["secret"]

            # NOTE(mnaser): We need to run as root in order to read the `cloud.conf`
            #               file from the host.
            doc["spec"]["template"]["spec"]["securityContext"] = {
                "runAsUser": 0,
            }

            # NOTE(mnaser): Because of the above, Kubernetes will not create a
            #               service account, so we make one manually.
            docs.append(
                {
                    "apiVersion": "v1",
                    "kind": "ServiceAccount",
                    "metadata": {
                        "name": "cloud-controller-manager",
                        "namespace": "kube-system",
                    },
                }
            )

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

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