---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later

- name: Generate account key
  openssl_privatekey:
    path: '{{ remote_tmp_dir }}/account.key'
    size: '{{ default_rsa_key_size }}'

- name: Generate privatekey
  openssl_privatekey:
    path: '{{ remote_tmp_dir }}/privatekey.pem'
    size: '{{ default_rsa_key_size }}'

- name: Generate CSRs
  openssl_csr:
    privatekey_path: '{{ remote_tmp_dir }}/privatekey.pem'
    path: '{{ remote_tmp_dir }}/{{ item.name }}.csr'
    subject_alt_name: '{{ item.sans }}'
  loop:
  - name: cert-1
    sans:
      - DNS:example.com
  - name: cert-2
    sans:
      - DNS:example.com
      - DNS:example.org

- name: Retrieve certificate 1
  x509_certificate:
    provider: acme
    path: '{{ remote_tmp_dir }}/cert-1.pem'
    csr_path: '{{ remote_tmp_dir }}/cert-1.csr'
    acme_accountkey_path: '{{ remote_tmp_dir }}/account.key'
    acme_challenge_path: '{{ remote_tmp_dir }}/challenges/'
    acme_directory: "{{ acme_directory_url }}"
  environment:
    PATH: '{{ lookup("env", "PATH") }}:{{ remote_tmp_dir }}'

- name: Get certificate information
  x509_certificate_info:
    path: '{{ remote_tmp_dir }}/cert-1.pem'
  register: result

- name: Validate certificate information
  assert:
    that:
      - result.subject_alt_name | length == 1
      - "'DNS:example.com' in result.subject_alt_name"

- name: Retrieve certificate 2
  x509_certificate:
    provider: acme
    path: '{{ remote_tmp_dir }}/cert-2.pem'
    csr_path: '{{ remote_tmp_dir }}/cert-2.csr'
    acme_accountkey_path: '{{ remote_tmp_dir }}/account.key'
    acme_challenge_path: '{{ remote_tmp_dir }}/challenges/'
    acme_directory: "{{ acme_directory_url }}"
  environment:
    PATH: '{{ lookup("env", "PATH") }}:{{ remote_tmp_dir }}'

- name: Get certificate information
  x509_certificate_info:
    path: '{{ remote_tmp_dir }}/cert-2.pem'
  register: result

- name: Validate certificate information
  assert:
    that:
      - result.subject_alt_name | length == 2
      - "'DNS:example.com' in result.subject_alt_name"
      - "'DNS:example.org' in result.subject_alt_name"
