- name: Check if PGP key is installed ({{ item.key }})
  command: "apt-key export {{ item.value.key_id }}"
  register: pgp_key
  failed_when: no
  changed_when: no

- set_fact:
    key_missing: "{{ 'nothing exported' in pgp_key.stderr }}"

- become: yes
  when: key_missing and item.key_url is defined
  block:
    - name: Download ES PGP key
      become: yes
      get_url:
        url: "{{ item.key_url }}"
        dest: /tmp/apt-repo.pgp
      when: key_missing

    - name: Install ES key
      become: yes
      command: apt-key add /tmp/apt-repo.pgp
      when: key_missing
      notify: apt update

    - name: rm /tmp/apt-repo.pgp
      become: yes
      file:
        path: /tmp/apt-repo.pgp
        state: absent
      when: key_missing

- name: "apt-key add {{ item.key }} (keyserver)"
  apt_key:
    id: "{{ item.value.key_id }}"
    keyserver: "{{ item.value.keyserver }}"
    state: "{{ state }}"
  when: key_missing and item.value.keyserver is defined and item.value.key_id is defined
  notify: apt update

- name: "add repo {{ item.key }}"
  when: item.value.url is defined and state == "present"
  vars:
    filename: "{{ item.filename | default(item.key) }}"
  copy:
    dest: "/etc/apt/sources.list.d/{{ item.key }}.list"
    content: |
      deb {{ item.value.url }} {{ item.value.distro }} {{ item.value.sections }}
  notify: apt update

- name: "remove repo {{ item.key }}"
  when: state == "absent"
  file:
    path: "/etc/apt/sources.list.d/{{ item.key }}.list"
    state: absent
  notify: apt update