---
#  WPA-Enterprise (EAP-TLS) - Check if certificate needs to be re-enrolled
- name: Check if certificate is already active on client
  ansible.builtin.stat:
    path: "/etc/ssl/certs/{{ wlan_ssid }}.crt"
  register: cert_client_active

- name: Extract serial from certificate
  ansible.builtin.command: 'openssl x509 -noout -serial -in /etc/ssl/certs/{{ wlan_ssid }}.crt'
  changed_when: false
  register: cert_serial
  when: cert_client_active.stat.exists

- name: Download crl from radius-server
  ansible.builtin.get_url:
    force: true
    mode: "0644"
    url: "{{ wlan_eap_ca_crl }}"
    dest: /tmp/radius-ca.crl
  when: cert_client_active.stat.exists

- name: Get radius-server ca crl
  community.crypto.x509_crl_info:
    path: /tmp/radius-ca.crl
    list_revoked_certificates: true
  register: radius_crl
  when: cert_client_active.stat.exists

- name: Check if radius-server is reachable
  ansible.builtin.command: echo "Test if radius-server is reachable"
  delegate_to: radius_server
  register: radius_reachable
  changed_when: false
  ignore_unreachable: true

- name: Inform that radius_server is unreachable
  ansible.builtin.debug:
    msg:
      - "Couldn't access radius_server. Possible reasons"
      - "* server not reachable"
      - "* no matching ssh-key"
  changed_when: true
  when: radius_reachable.unreachable is defined and radius_reachable.unreachable

- name: Issue radius certificate
  ansible.builtin.include_tasks: eap-tls_issue-certificate.yaml
  when:
    - radius_reachable.unreachable is not defined or not radius_reachable.unreachable
    - |
      ( not cert_client_active.stat.exists ) or
      (cert_serial.stdout | replace('serial=','') | int(base=16) ) in ( radius_crl.revoked_certificates | map(attribute='serial_number') | list ) or
      wlan_force_issue
