---
- name: Initialize the Kubernetes cluster
  ansible.builtin.shell: kubeadm init --pod-network-cidr=10.244.0.0/16
  when: is_control_plane | bool
  register: init_output
  ignore_errors: yes

- name: Capture the kubeadm join command
  set_fact:
    join_command: "{{ init_output.stdout_lines | select('search','kubeadm join') | list | first }}"
  ignore_errors: yes

- name: Debug print the kubeadm join command
  ansible.builtin.debug:
    msg: 'The captured kubeadm join command is: {{ join_command }}'
  when:
    - is_control_plane | bool
    - join_command is defined

- name: Join the node to the Kubernetes cluster
  ansible.builtin.shell: '{{ join_command }} --discovery-token-unsafe-skip-ca-verification'
  ignore_errors: yes
  when:
    - "'worker_nodes' in group_names"
    - join_command is defined

- name: Ensure Kubernetes directory exists
  ansible.builtin.file:
    path: '/etc/kubernetes/'
    state: directory
  when: is_control_plane | bool

- name: Ensure .kube directory exists in user's home
  ansible.builtin.file:
    path: '{{ ansible_env.HOME }}/.kube'
    state: directory
    mode: '0755'

- name: Copy admin.conf to user's .kube directory
  ansible.builtin.copy:
    src: /etc/kubernetes/admin.conf
    dest: '{{ ansible_env.HOME }}/.kube/config'
    remote_src: yes
    owner: '{{ ansible_env.USER }}'
    group: '{{ ansible_env.USER }}'
    mode: '0644'
  when: is_control_plane | bool
