---
- name: Converge
  hosts: all
  gather_facts: false
  vars:
    cert_export_path: "{{ lookup('env', 'path_for_import_cert') }}"

  tasks:
    - name: Set fact
      ansible.builtin.set_fact:
        per_mode: "0755"

    - name: Create Directory
      ansible.builtin.file:
        path: "{{ cert_export_path }}"
        state: directory
        mode: "{{ per_mode }}"
      register: idrac_certificate_created_directory
      check_mode: false

    - name: Generate HTTPS CSR signing request
      ansible.builtin.import_role:
        name: idrac_certificate
      vars:
        hostname: "{{ lookup('env', 'IDRAC_IP') }}"
        username: "{{ lookup('env', 'IDRAC_USER') }}"
        password: "{{ lookup('env', 'IDRAC_PASSWORD') }}"
        validate_certs: false
        command: "generate_csr"
        certificate_type: "HTTPS"
        certificate_path: "{{ cert_export_path }}"
        cert_params:
          common_name: "sample.domain.com"
          organization_unit: "OrgUnit"
          locality_name: "Bangalore"
          state_name: "Karnataka"
          country_code: "IN"
          email_address: "admin@domain.com"
          organization_name: "OrgName"
          subject_alt_name:
            - "hostname1.chassis.com"

    - name: Setting up HTTPS CSR certificate path for exported file
      ansible.builtin.stat:
        path: "{{ idrac_certificate_out.certificate_path }}"
      register: csr_cert_file
      no_log: true

    - name: Verifying HTTPS generate CSR certificate
      ansible.builtin.assert:
        that:
          - csr_cert_file.stat.exists
          - not idrac_certificate_out.changed
          - not idrac_certificate_out.failed
          - idrac_certificate_out.msg == "Successfully performed the 'generate_csr' certificate operation."
