- name: Install required packages
  ansible.builtin.apt:
    update_cache: yes
    name:
      - software-properties-common
      - curl
      - git
    state: present

- name: Check if Kubernetes APT keyring exists
  ansible.builtin.stat:
    path: /etc/apt/keyrings/kubernetes-apt-keyring.gpg
  register: kubernetes_keyring

- name: Add Kubernetes APT keyring
  ansible.builtin.shell: |
    curl -fsSL https://pkgs.k8s.io/core:/stable:/{{ kubernetes_version }}/deb/Release.key | gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
  when: not kubernetes_keyring.stat.exists
  register: apt_keyring_result
  ignore_errors: yes

- name: Check if CRI-O APT keyring exists
  ansible.builtin.stat:
    path: /etc/apt/keyrings/cri-o-apt-keyring.gpg
  register: cri_o_keyring

- name: Add CRI-O APT keyring
  ansible.builtin.shell: |
    curl -fsSL https://pkgs.k8s.io/addons:/cri-o:/{{ project_path }}/deb/Release.key | gpg --dearmor -o /etc/apt/keyrings/cri-o-apt-keyring.gpg
  when: not cri_o_keyring.stat.exists
  ignore_errors: yes

- name: Update APT cache after adding keys
  ansible.builtin.apt:
    update_cache: yes

- name: Add Kubernetes APT repository
  ansible.builtin.lineinfile:
    path: /etc/apt/sources.list.d/kubernetes.list
    line: 'deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/{{ kubernetes_version }}/deb/ /'
    create: yes
  ignore_errors: yes

- name: Add CRI-O APT repository
  ansible.builtin.lineinfile:
    path: /etc/apt/sources.list.d/cri-o.list
    line: 'deb [signed-by=/etc/apt/keyrings/cri-o-apt-keyring.gpg] https://pkgs.k8s.io/addons:/cri-o:/{{ project_path }}/deb/ /'
    create: yes
  ignore_errors: yes

- name: Install Kubernetes components and CRI-O
  ansible.builtin.apt:
    update_cache: yes
    name:
      - cri-o
      - kubelet
      - kubeadm
      - kubectl
    state: latest

- name: Start CRI-O service
  ansible.builtin.systemd:
    name: crio
    state: started
    enabled: yes

- name: Disable swap
  ansible.builtin.shell: swapoff -a
  notify: Apply sysctl settings

- name: Load br_netfilter module
  ansible.builtin.modprobe:
    name: br_netfilter
    state: present

- name: Enable IP forwarding
  ansible.builtin.sysctl:
    name: net.ipv4.ip_forward
    value: '1'
    state: present
    reload: yes

- name: Configure kubelet for external cloud provider
  ansible.builtin.lineinfile:
    path: /usr/lib/systemd/system/kubelet.service.d/10-kubeadm.conf
    regexp: '^ExecStart=.*'
    line: 'ExecStart=/usr/bin/kubelet $KUBELET_KUBECONFIG_ARGS $KUBELET_CONFIG_ARGS $KUBELET_KUBEADM_ARGS $KUBELET_EXTRA_ARGS --cloud-provider=external'
    backrefs: yes

- name: Reload systemd daemon to apply kubelet configuration changes
  ansible.builtin.systemd:
    daemon_reload: yes

- name: Restart kubelet to apply external cloud provider configuration
  ansible.builtin.service:
    name: kubelet
    state: restarted
