---
- name: Issue simple self-signed certificate
  hosts: all

  vars:
    certificate_requests:
      - name: mycert_run_hooks
        dns: www.example.com
        ca: self-sign
        run_before: >
          touch /etc/pki/before_cert.tmp
        run_after: >
          touch /etc/pki/after_cert.tmp
  roles:
    - fedora.linux_system_roles.certificate

- name: Verify certificate
  hosts: all
  vars:
    certificates:
      - path: /etc/pki/tls/certs/mycert_run_hooks.crt
        key_path: /etc/pki/tls/private/mycert_run_hooks.key
        subject:
          - name: commonName
            oid: 2.5.4.3
            value: www.example.com
        subject_alt_name:
          - name: DNS
            value: www.example.com
  tasks:
    - name: Verify each certificate
      include_tasks: tasks/assert_certificate_parameters.yml
      loop: "{{ certificates }}"
      loop_control:
        loop_var: cert

    - name: Verify test files timestamp
    # certmonger does not actually run in buildah
      when: ansible_connection != "buildah"
      block:
        - name: Get certificate timestamp
          stat:
            path: "{{ certificates[0].path }}"
          register: cert_result
        - name: Get pre-run file timestamp
          stat:
            path: /etc/pki/before_cert.tmp
          register: before_result
        - name: Get post-run file timestamp
          stat:
            path: /etc/pki/after_cert.tmp
          register: after_result
        - name: Assert file created before cert
          assert:
            that:
              - before_result.stat.mtime <= cert_result.stat.mtime
            fail_msg: >-
              {{ before_result.stat.mtime }} >
              {{ cert_result.stat.mtime }}
        - name: Assert file created after cert
          assert:
            that:
              - after_result.stat.mtime >= cert_result.stat.mtime
            fail_msg: >-
              {{ after_result.stat.mtime }} <
              {{ cert_result.stat.mtime }}

    - name: Get pre/post-scripts files
      find:
        paths:
          - /etc/certmonger/pre-scripts
          - /etc/certmonger/post-scripts
        file_type: file
      register: __script_files

    - name: Check generated files for ansible_managed, fingerprint
      include_tasks: tasks/check_header.yml
      loop: "{{ __script_files.files | map(attribute='path') | list }}"
      loop_control:
        loop_var: __file
      vars:
        __fingerprint: "system_role:certificate"
