---

- name: Populate service facts
  service_facts:

- name: Ensure any worker services are stopped
  service:
    name: "{{ item.key }}"
    state: stopped
  with_dict: "{{ ansible_facts.services|default({})|dict2items|selectattr('key', 'match', 'matrix-synapse-worker@.+\\.service')|list|items2dict }}"

- name: Ensure worker service symlinks are cleaned
  file:
    path: "{{ item.root + '/' + item.path }}"
    state: absent
  when:
    - item.state == 'link'
    - item.path is match('matrix-synapse-worker@.*\\.service')
  with_filetree:
    - "{{ matrix_systemd_path }}/matrix-synapse.service.wants"

- name: Ensure synapse worker base service file gets removed
  file:
    path: "{{ matrix_systemd_path }}/matrix-synapse-worker@.service"
    state: absent
  register: matrix_synapse_worker_systemd_service_result

- name: Ensure worker configs are cleaned
  file:
    path: "{{ item }}"
    state: absent
  with_fileglob:
    - "{{ matrix_synapse_config_dir_path }}/worker.*.yaml"

- name: Remove workers from synapse.wants list
  set_fact:
    matrix_synapse_systemd_wanted_services_list: "{{ matrix_synapse_systemd_wanted_services_list | reject('search', '^matrix-synapse-worker@') | list }}"

- name: Ensure systemd noticed removal of worker service units
  service:
    daemon_reload: yes

- name: Ensure matrix-synapse-worker-write-pid script is removed
  file:
    path: "{{ matrix_local_bin_path }}/matrix-synapse-worker-write-pid"
    state: absent