---
- name: Check if k3s agent service exists
  stat:
    path: /etc/systemd/system/k3s-agent.service
  register: k3s_agent_service

- name: Check k3s agent service state
  command: systemctl is-active k3s-agent
  register: k3s_agent_service_state
  changed_when: false
  failed_when: false
  when: k3s_agent_service.stat.exists

- name: Determine whether k3s agent install is needed
  set_fact:
    k3s_agent_install_needed: "{{ (not k3s_agent_service.stat.exists) or ((k3s_agent_service_state.stdout | default('')) != 'active') }}"

- name: Download k3s install script
  get_url:
    url: https://get.k3s.io
    dest: /tmp/install-k3s.sh
    mode: "0755"
  when: k3s_agent_install_needed

- name: Install k3s agent
  when: k3s_agent_install_needed
  block:
    - name: Run k3s agent install
      environment:
        INSTALL_K3S_VERSION: "{{ k3s_version if k3s_version != 'latest' else '' }}"
        K3S_URL: "{{ k3s_server_url }}"
        K3S_TOKEN: "{{ k3s_token }}"
      command: >-
        /tmp/install-k3s.sh agent
        --node-ip {{ k3s_node_ip }}
        --flannel-iface={{ k3s_flannel_iface }}
        {% if k3s_kubelet_cloud_provider_external | bool %}--kubelet-arg=cloud-provider=external{% endif %}
      register: k3s_agent_install
      failed_when: false
      args:
        creates: /usr/local/bin/k3s-agent

- name: Wait for k3s agent to be ready
  command: systemctl is-active k3s-agent
  register: agent_status
  until: agent_status.stdout == "active"
  retries: 30
  delay: 10
  changed_when: false

- name: Show k3s-agent service status on failure
  command: systemctl status k3s-agent --no-pager
  register: k3s_agent_status
  changed_when: false
  failed_when: false
  when: agent_status is failed

- name: Show recent k3s-agent logs on failure
  command: journalctl -u k3s-agent -n 120 --no-pager
  register: k3s_agent_journal
  changed_when: false
  failed_when: false
  when: agent_status is failed

- name: Fail with k3s-agent diagnostics
  fail:
    msg: |
      k3s agent failed to become ready on {{ inventory_hostname }}.
      Install stdout:
      {{ k3s_agent_install.stdout | default('n/a') }}

      Install stderr:
      {{ k3s_agent_install.stderr | default('n/a') }}

      Service status:
      {{ k3s_agent_status.stdout | default('n/a') }}

      Recent logs:
      {{ k3s_agent_journal.stdout | default('n/a') }}
  when: agent_status is failed
