---
- name: Create private key for client certificate
  community.crypto.openssl_privatekey:
    path: /etc/ssl/private/{{ ssid }}.key

- name: Create CSR for client certificate
  community.crypto.openssl_csr_pipe:
    common_name: "{{ ansible_hostname }}"
    country_name: "{{ country_name }}"
    state_or_province_name: "{{ state_or_province_name }}"
    locality_name: "{{ locality_name }}"
    organization_name: "{{ organization_name }}"
    privatekey_path: /etc/ssl/private/{{ ssid }}.key
    email_address: "{{ admin_email }}"
  register: csr

- name: Sign CSR on Radius
  community.crypto.x509_certificate_pipe:
    csr_content: "{{ csr.csr }}"
    provider: ownca
    ownca_path: /etc/freeradius/3.0/certs/ca.pem
    ownca_privatekey_path: /etc/freeradius/3.0/certs/ca.key
    ownca_privatekey_passphrase: "{{ radiusca_password }}"
    ownca_not_after: +1825d # 5 Years
  delegate_to: radius_server
  register: certificate

- name: Create issued-Notice folder on radius-server
  ansible.builtin.file:
    dest: "/etc/freeradius/3.0/certs/issued"
    state: directory
    mode: '0755'
  delegate_to: radius_server

- name: Write certificate to client
  ansible.builtin.copy:
    dest: /etc/ssl/certs/{{ ssid }}.crt
    mode: '0644'
    content: "{{ certificate.certificate }}"

- name: Extract Serial from Certificate
  ansible.builtin.command: 'openssl x509 -noout -serial -in /etc/ssl/certs/{{ ssid }}.crt'
  register: cert_serial
  changed_when: cert_serial.rc != 0

- name: Create issued-Notice-file on radius-server
  ansible.builtin.copy:
    dest: "/etc/freeradius/3.0/certs/issued/{{ ansible_hostname }}"
    mode: '0644'
    content: "{{ cert_serial.stdout }}"
  delegate_to: radius_server

- name: Check if NetworkManager config exists {{ ssid }}
  ansible.builtin.stat:
    path: /etc/NetworkManager/system-connections/{{ ssid }}.nmconnection
  register: nm_connection

- name: Create or modify connection via nmcli {{ ssid }}
  ansible.builtin.command: >
    nmcli c {% if nm_connection.stat.exists %} modify {{ ssid }} {% else %} add {% endif %}
    type wifi
    ifname {{ ansible_interfaces | select('search', 'wl.+') | first }}
    con-name "{{ ssid }}"
    connection.permissions ""
    802-11-wireless.ssid "{{ ssid }}"
    802-11-wireless-security.key-mgmt wpa-eap
    802-1x.eap tls
    802-1x.identity {{ ansible_hostname }}
    802-1x.client-cert /etc/ssl/certs/{{ ssid }}.crt
    802-1x.private-key /etc/ssl/private/{{ ssid }}.key
    802-1x.private-key-password dummy
