---
- name: Set external kube-apiserver endpoint
  set_fact:
    # noqa: jinja[spacing]
    external_apiserver_address: >-
      {%- if loadbalancer_apiserver is defined and loadbalancer_apiserver.address is defined -%}
      {{ loadbalancer_apiserver.address }}
      {%- elif kubeconfig_localhost_ansible_host is defined and kubeconfig_localhost_ansible_host -%}
      {{ hostvars[groups['kube_control_plane'][0]].ansible_host }}
      {%- else -%}
      {{ kube_apiserver_access_address }}
      {%- endif -%}
    # noqa: jinja[spacing]
    external_apiserver_port: >-
      {%- if loadbalancer_apiserver is defined and loadbalancer_apiserver.address is defined and loadbalancer_apiserver.port is defined -%}
      {{ loadbalancer_apiserver.port | default(kube_apiserver_port) }}
      {%- else -%}
      {{ kube_apiserver_port }}
      {%- endif -%}
  tags:
    - facts

- name: Create kube config dir for current/ansible become user
  file:
    path: "{{ ansible_env.HOME | default('/root') }}/.kube"
    mode: "0700"
    state: directory

- name: Write admin kubeconfig to current/ansible become user home
  copy:
    src: "{{ kube_config_dir }}/admin.conf"
    dest: "{{ ansible_env.HOME | default('/root') }}/.kube/config"
    remote_src: true
    mode: "0600"
    backup: true

- name: Create kube artifacts dir
  file:
    path: "{{ artifacts_dir }}"
    mode: "0750"
    state: directory
  delegate_to: localhost
  connection: local
  become: false
  run_once: true
  when: kubeconfig_localhost

- name: Wait for k8s apiserver
  wait_for:
    host: "{{ kube_apiserver_access_address }}"
    port: "{{ kube_apiserver_port }}"
    timeout: 180

- name: Create kubeconfig localhost artifacts
  when: kubeconfig_localhost
  block:
    - name: Generate admin kubeconfig using kubeadm
      command: >-
        {{ bin_dir }}/kubeadm kubeconfig user
        --client-name=kubernetes-admin-{{ cluster_name }}
        --org=kubeadm:cluster-admins
        --config {{ kube_config_dir }}/kubeadm-config.yaml
      register: kubeadm_admin_kubeconfig
      changed_when: false
      run_once: true
      delegate_to: "{{ groups['kube_control_plane'][0] }}"

    - name: Write admin kubeconfig on ansible host
      copy:
        content: "{{ kubeadm_admin_kubeconfig.stdout | from_yaml | combine(override, recursive=true) | to_nice_yaml(indent=2) }}"
        dest: "{{ artifacts_dir }}/admin.conf"
        mode: "0600"
      vars:
        admin_kubeconfig: "{{ kubeadm_admin_kubeconfig.stdout | from_yaml }}"
        context: "kubernetes-admin-{{ cluster_name }}@{{ cluster_name }}"
        override:
          clusters:
            - "{{ admin_kubeconfig['clusters'][0] | combine({'name': cluster_name, 'cluster': admin_kubeconfig['clusters'][0]['cluster'] | combine({'server': 'https://' + (external_apiserver_address | ansible.utils.ipwrap) + ':' + (external_apiserver_port | string)})}, recursive=true) }}"
          contexts:
            - "{{ admin_kubeconfig['contexts'][0] | combine({'name': context, 'context': admin_kubeconfig['contexts'][0]['context'] | combine({'cluster': cluster_name})}, recursive=true) }}"
          current-context: "{{ context }}"
      delegate_to: localhost
      connection: local
      become: false
      run_once: true

- name: Copy kubectl binary to ansible host
  fetch:
    src: "{{ bin_dir }}/kubectl"
    dest: "{{ artifacts_dir }}/kubectl"
    flat: true
    validate_checksum: false
  register: copy_binary_result
  until: copy_binary_result is not failed
  retries: 20
  become: false
  run_once: true
  when: kubectl_localhost

- name: Create helper script kubectl.sh on ansible host
  copy:
    content: |
      #!/bin/bash
      ${BASH_SOURCE%/*}/kubectl --kubeconfig=${BASH_SOURCE%/*}/admin.conf "$@"
    dest: "{{ artifacts_dir }}/kubectl.sh"
    mode: "0755"
  become: false
  run_once: true
  delegate_to: localhost
  connection: local
  when: kubectl_localhost and kubeconfig_localhost
