---
- name: "Ensure directory"
  file:
    path: '{{ selfsigned_ca_cert_private_key | dirname }}'
    state: directory
    mode: '0755'

- name: "Generate an OpenSSL private key"
  community.crypto.openssl_privatekey:
    path: '{{ selfsigned_ca_cert_private_key }}'
    backup: yes
    regenerate: full_idempotence
    size: 4096
    type: RSA
    group: '{{ selfsigned_ca_cert_private_key_group | default("root") }}'
    mode: '0640'

- name: "Create certificate signing request (CSR) for new certificate"
  community.crypto.openssl_csr_pipe:
    privatekey_path: '{{ selfsigned_ca_cert_private_key }}'
    subject: '{{ selfsigned_ca_cert_subject }}'
    subject_alt_name: '{{ selfsigned_ca_cert_altnames | list }}'
  run_once: true
  register: csr

- name: "Sign certificate with our CA"
  community.crypto.x509_certificate_pipe:
    csr_content: "{{ csr.csr }}"
    provider: ownca
    ownca_path: '{{ selfsigned_ca_dir }}/ca-certificate.pem'
    ownca_privatekey_path: '{{ selfsigned_ca_dir }}/ca-certificate.key'
    ownca_privatekey_passphrase: "{{ selfsigned_ca_private_key_passphrase }}"
    ownca_not_after: +1000d
    ownca_not_before: "-3d"
  run_once: true
  register: certificate

- name: "Write certificate file"
  copy:
    dest: '{{ selfsigned_ca_cert_public_key }}'
    mode: '0644'
    content: "{{ certificate.certificate }}"
  run_once: true
  notify: '{{ selfsigned_ca_trigger_handler | default([]) }}'

- name: "Write CA certificate"
  copy:
    src: '{{ selfsigned_ca_dir }}/ca-certificate.pem'
    mode: '0644'
    remote_src: yes
    dest: '{{ selfsigned_ca_cacert }}'
  run_once: true
  notify: '{{ selfsigned_ca_trigger_handler | default([]) }}'
