---
- name: Configure time synchronization with NTP servers and PTP domains
  hosts: all
  gather_facts: true
  vars:
    timesync_ntp_servers:
      - hostname: 172.16.123.1
        minpoll: 0
        maxpoll: 2
      - hostname: 172.16.123.2
        minpoll: 0
        maxpoll: 2
    timesync_ptp_domains:
      - number: 0
        interfaces: "{{ [ ansible_default_ipv4['interface'] ] }}"
        delay: 0.0001
      - number: 1
        interfaces: "{{ [ ansible_default_ipv4['interface'] ] }}"
        delay: 0.0001
    timesync_step_threshold: 0.001
    timesync_dhcp_ntp_servers: false
    timesync_min_sources: 2
  tasks:
    - name: Run test
      tags: tests::verify
      block:
        - name: Common test setup tasks
          include_tasks: tasks/setup.yml

        - name: Run role
          include_role:
            name: linux-system-roles.timesync
            public: true

        - name: Flush handlers
          meta: flush_handlers

        - name: Ensure ethtool is installed
          package:
            name: ethtool
            state: present
            use: "{{ (__timesync_is_ostree | d(false)) |
                     ternary('ansible.posix.rhel_rpm_ostree', omit) }}"

        - name: Check if SW/HW timestamping is supported
          command: ethtool -T "{{ ansible_default_ipv4['interface'] }}"
          register: ethtool
          ignore_errors: true  # noqa ignore-errors
          changed_when: false

        - name: Run test
          when: "'ware-transmit' in ethtool.stdout"
          block:
            - name: Wait for services to start
              wait_for:
                timeout: 2

            - name: Get list of currently used time sources
              shell: chronyc -n sources || ntpq -pn
              register: sources
              changed_when: false

            - name: Check time sources
              assert:
                that:
                  - "'172.16.123.1' in sources.stdout"
                  - "'172.16.123.2' in sources.stdout"
                  - "'PTP0' in sources.stdout"
                  - "'PTP1' in sources.stdout"

      always:
        - name: Cleanup after tests
          include_tasks: tasks/cleanup.yml
          vars:
            timesync_ntp_servers: []
            timesync_ptp_domains: []
