---

- name: "Check if ansible version is at least {{ ansible_minimal_version }}"
  assert:
    that:
      - ansible_version.string is version(ansible_minimal_version, ">=")
    msg: "The ansible version has to be at least {{ ansible_minimal_version }}"
  tags:
    - always

- name: "Reading all role versions and set versions as facts"
  set_fact:
    hetzner_ansible_roles:
      - "hetzner-ansible-common"
      - "hetzner-ansible-dns"
      - "hetzner-ansible-filebeat"
      - "hetzner-ansible-hcloud"
      - "hetzner-ansible-metricbeat"
      - "hetzner-ansible-node-exporter"
      - "hetzner-ansible-traefik"
      - "hetzner-ansible-sma-deploy"
  tags:
    - always

- name: "Read galaxy-requirements file"
  ansible.builtin.command: "cat galaxy-requirements.yml"
  register: galaxy_requirements_txt
  changed_when: false
  connection: local

- name: "Parse galaxy-requirements file into variable"
  set_fact:
    galaxy_requirements_json: "{{ galaxy_requirements_txt.stdout | from_yaml }}"

- name: "Reading all role versions and set versions as facts (galaxy-requirements)" # noqa var-naming
  set_fact:
    {"{{ item | replace('-','_') }}_current_version":"{{ galaxy_requirements_json.roles | selectattr('name','equalto',item) | map(attribute='version') | first | default('version_not_available') }}"}
  loop: "{{ hetzner_ansible_roles }}"
  tags:
    - always

- name: "Reading all role versions and set versions as facts (role)"
  include_role:
    name: "{{ item }}"
    tasks_from: _get_version.yml
  loop: "{{ hetzner_ansible_roles }}"
  tags:
    - always

- name: "Printing role versions"
  debug:
    msg: "<{{ item }}> : <{{ lookup('vars', item | replace('-','_') + '_current_version') }}> : <{{ lookup('vars', item | replace('-','_') + '_version') }}>"
  loop: "{{ hetzner_ansible_roles }}"
  tags:
    - always

- name: "Check role versions"
  assert:
    that:
      - "'{{ lookup('vars', item | replace('-', '_') + '_version') }}' == '{{ lookup('vars', item | replace('-', '_') + '_current_version') }}'"
    msg: "The current {{ item }} version has to be {{ lookup('vars', item | replace('-','_') + '_current_version') }}"
  loop: "{{ hetzner_ansible_roles }}"
  tags:
    - always
