
from utility import configureKustomization, getFolderName, getServiceName, patchKustomizationFile
import yaml
import ruamel.yaml
def generateEndpointYaml():
    folderName = getFolderName()
    yaml_data = {
        "apiVersion": "apps/v1",
        "kind": "Deployment",
        "metadata": {
            "name": "nse-kernel",
            "labels": {
                "app": "nse-kernel"
            }
        },
        "spec": {
            "selector": {
                "matchLabels": {
                    "app": "nse-kernel"
                }
            },
            "template": {
                "metadata": {
                    "labels": {
                        "app": "nse-kernel",
                        "spiffe.io/spiffe-id": "\"true\""
                    }
                },
                "spec": {
                    "containers": [
                        {
                            "name": "nse",
                            "image": "ghcr.io/networkservicemesh/ci/cmd-nse-icmp-responder:6235cf9",
                            "imagePullPolicy": "IfNotPresent",
                            "securityContext": {
                                "privileged": True
                            },
                            "env": [
                                {
                                    "name": "SPIFFE_ENDPOINT_SOCKET",
                                    "value": "unix:///run/spire/sockets/agent.sock"
                                },
                                {
                                    "name": "POD_NAME",
                                    "valueFrom": {
                                        "fieldRef": {
                                            "fieldPath": "metadata.name"
                                        }
                                    }
                                },
                                {
                                    "name": "NSM_NAME",
                                    "value": "$(POD_NAME)"
                                },
                                {
                                    "name": "NSM_LOG_LEVEL",
                                    "value": "TRACE"
                                },
                                {
                                    "name": "NSM_CONNECT_TO",
                                    "value":  "unix:///var/lib/networkservicemesh/nsm.io.sock"
                                }
                            ],
                            "volumeMounts": [
                                {
                                    "name": "spire-agent-socket",
                                    "mountPath": "/run/spire/sockets",
                                    "readOnly": True
                                },
                                {
                                    "name": "nsm-socket",
                                    "mountPath": "/var/lib/networkservicemesh",
                                    "readOnly": True
                                },
                            ],
                            "resources": {
                                "requests": {
                                    "cpu": "100m",
                                    "memory": "40Mi"
                                },
                                "limits": {
                                    "memory": "80Mi",
                                    "cpu": "200m"
                                }
                            }
                        }
                    ],
                    "volumes": [
                        {
                            "name": "spire-agent-socket",
                            "hostPath": {
                                "path": "/run/spire/sockets",
                                "type": "Directory"
                            }
                        },
                        {
                            "name": "nsm-socket",
                            "hostPath": {
                                "path": "/var/lib/networkservicemesh",
                                "type": "DirectoryOrCreate"
                            }
                        },
                    ]
                }
            }
        }
    }

    ruamel.yaml.YAML().default_style=None
    filename="nse.yaml"
    with open(folderName+"/"+filename, "w") as yaml_file:
           ruamel.yaml.YAML().dump(yaml_data, yaml_file)
    configureKustomization(filename)
    patchNseYaml()


def patchNseYaml():
    folderName = getFolderName()
    with open(folderName+"/ns.yaml", 'r') as file:
        ns_yaml = yaml.load(file, Loader=yaml.FullLoader)
        #This part is needed to retrieve the label used in network service to identify the last endpoint
        #Is then used as "NSM_LABELS" env in the yaml file
        matches = ns_yaml.get('spec', {}).get('matches', [])
        last_app_value = None
        
        for match in matches[::-1]:  #Get the last values starting from the end.
            destination_selector = match.get('routes', [{}])[0].get('destination_selector', {})
            if 'app' in destination_selector:
                last_app_value = destination_selector['app']
                break
    #Writes the 'patch-nse.yaml' file       
    yaml_data = {
        "apiVersion": "apps/v1",
        "kind": "Deployment",
        "metadata": {
            "name": "nse-kernel"
        },
        "spec": {
            "template": {
                "spec": {
                    "containers": [
                        {
                            "name": "nse",
                            "env": [
                                {
                                    "name": "NSM_CIDR_PREFIX",
                                    "value": "172.16.3.0/31"
                                },
                                {
                                    "name": "NSM_SERVICE_NAMES",
                                    "value": "\"security-chain\""
                                },
                                {
                                    "name": "NSM_REGISTER_SERVICE",
                                    "value": "false"
                                },
                                {
                                    "name": "NSM_LABELS",
                                    "value":f"app:{last_app_value}"
                                }
                            ]
                        },
                    ],
                }
            }
        }
    }
    filename ="patch-nse.yaml"
    # Scrittura dei dati nel file deployment.yaml
    with open(folderName + "/patch-nse.yaml", 'w') as file:
        ruamel.yaml.YAML().dump(yaml_data, file)
    patchKustomizationFile(filename)