- 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: Check if kubeadm join command was captured
  set_fact:
    join_command: "{{ init_output.stdout_lines | select('search','kubeadm join') | list | first }}"
  when:
    - is_control_plane | bool
    - init_output.stdout_lines is defined
  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: Set KUBECONFIG environment variable for the root user
  ansible.builtin.lineinfile:
    path: /root/.bashrc
    line: 'export KUBECONFIG=/etc/kubernetes/admin.conf'
    create: yes
  when: is_control_plane | bool

- name: Download admin.conf to localhost for local kubectl access
  ansible.builtin.fetch:
    src: /etc/kubernetes/admin.conf
    dest: '{{ playbook_dir }}/admin.conf'
    flat: yes
  when: is_control_plane | bool

- name: 'Join the node to the Kubernetes cluster'
  vars:
    join_command_modified: "{{ hostvars[groups['control_plane'][0]].join_command[:-2] }}"
  ansible.builtin.shell: '{{ join_command_modified }} --discovery-token-unsafe-skip-ca-verification'
  when:
    - "'worker_nodes' in group_names"
  ignore_errors: true
  register: join_result

- name: 'Debug - Check join result'
  ansible.builtin.debug:
    var: join_result
  when: "'worker_nodes' in group_names"
