import yaml
import re


def create_kubeconfig_for_ssh_tunnel(kubeconfig_file, kubeconfig_target_file):
    """
        Creates a kubeconfig in which the Server URL is modified to use a locally set up SSH tunnel. (using 127.0.0.1 as an address)

        Returns a tuple consisting of: 
            - the original IP/Servername of the K8s API
            - the original Port of the K8s API
    """
    with open (kubeconfig_file, "r") as f:
        kubeconfig = yaml.load(f.read(), Loader=yaml.FullLoader)

    original_server_address = kubeconfig["clusters"][0]["cluster"]["server"]

    address_pattern = re.compile('https://([^:]*):([0-9]+)')

    match = address_pattern.match(original_server_address)

    if not match:
        print('Error: No API address found in kubeconfig')
        exit(1)

    original_api_hostname = match.group(1)
    original_api_port = match.group(2)

    kubeconfig["clusters"][0]["cluster"]["server"] = f"https://127.0.0.1:{original_api_port}"

    with open (kubeconfig_target_file, "w") as f:
        f.write(yaml.dump(kubeconfig, default_flow_style=False))
        f.close()

    return (original_api_hostname, original_api_port)