---
# yamllint disable rule:line-length
- name: Test using an existing certificate with cockpit
  hosts: all
  tasks:
    - name: Include role
      include_role:
        name: linux-system-roles.cockpit
        public: true
      vars:
        cockpit_packages: minimal
        cockpit_cert: /etc/myserver.crt
        cockpit_private_key: /etc/myserver.key

    - name: Collect installed package versions
      package_facts:

    - name: Check if cockpit is new enough (at least 257) to support existing certificates
      when: ansible_facts.packages['cockpit-ws'][0].version | int >= 257
      block:
        - name: Create test certificate key
          command: openssl ecparam -name secp521r1 -genkey -out /etc/myserver.key
          args:
            creates: /etc/myserver.key

        - name: Create test certificate cert
          command: openssl req -new -x509 -key /etc/myserver.key -subj '/CN=localhost' -out /etc/myserver.crt -days 365
          args:
            creates: /etc/myserver.crt

        # ostree cannot remove packages and cannot cleanup properly
        # this works around that issue
        - name: Restart cockpit to use the new certificates
          service:
            name: "{{ __cockpit_daemon }}"
            state: restarted
          when: __cockpit_is_ostree | d(false)

        - name: Test - cockpit works with TLS and expected certificate
          # noqa command-instead-of-module
          command:
            cmd: curl --cacert /etc/myserver.crt https://localhost:9090
            # ansible 2.11's uri module has ca_path, but that's still too new for us
          changed_when: false
          when: __cockpit_is_booted

      always:
        - name: Cleanup - test certificate cert
          file:
            path: /etc/myserver.crt
            state: absent
          tags:
            - always
            - tests::cleanup

        - name: Cleanup - test certificate key
          file:
            path: /etc/myserver.key
            state: absent
          tags:
            - always
            - tests::cleanup

        - name: Cleanup
          include_tasks: tasks/cleanup.yml
