---
- name: Ensure service facts are available
  ansible.builtin.service_facts:

# - name: Capture a list of running services
#   ansible.builtin.set_fact:
#     bigboot_systemd_running_services:
#       "{{ bigboot_systemd_running_services | default([]) + [item['key']] }}"
#   loop: "{{ ansible_facts['services'] | dict2items }}"
#   loop_control:
#     label: "{{ item['key'] }}"
#   when:
#     - "'running' in item['value']['state']"

# - name: Get the stop timeout value for running services
#   ansible.builtin.shell:
#     cmd: |
#       set -o pipefail
#       systemctl show {{ item }} | grep TimeoutStopUSec
#   changed_when: false
#   register: bigboot_systemd_service_timeout
#   loop: "{{ bigboot_systemd_running_services }}"

# - name: Adding services exceeding the timeout threshold to the list of services to disable
#   ansible.builtin.set_fact:
#     bigboot_services_disabled: "{{ bigboot_services_disabled | default([]) + [item['item']] }}"
#   loop: "{{ bigboot_systemd_service_timeout['results'] }}"
#   loop_control:
#     label: "{{ item['item'] }}"
#   when:
#     - item['item'] not in bigboot_protected_services
#     - item['stdout'] | regex_replace('^.*=(.*$)', '\\1') | community.general.to_minutes >= bigboot_service_max_timeout | int

- name: Adding incompatible services to the list of services to disable
  ansible.builtin.set_fact:
    bigboot_services_disabled: "{{ bigboot_services_disabled | default([]) + [item] }}"
  loop: "{{ bigboot_incompatible_services }}"
  when:
    - ansible_facts['services'][item] is defined
    - ansible_facts['services'][item]['state'] == "running"

- name: Log and disable services
  when:
    - bigboot_services_disabled is defined
    - bigboot_services_disabled | length > 0
  block:
    - name: Disable services and log their state
      ansible.builtin.include_tasks: tasks/disable_systemd_services.yml
      loop: "{{ bigboot_services_disabled }}"

    - name: Services disabled notice
      ansible.builtin.debug:
        msg: >-
          The following services were disabled, and will be re-enabled post
          Bigboot execution: {{ bigboot_services_disabled | join(', ') }}

