---

- name: (systemd-services.yml) Check if Service Exists (Debian based OS)
  shell: 'systemctl list-unit-files | grep -q -e "^{{ item }}.service";'
  changed_when: "service_exists.rc > 1"
  failed_when: "service_exists.rc > 1"
  register: service_exists
  with_items: 
    - "{{ debian_services_active_and_started }}"

#- debug: msg="{{ service_exists.results }}"

- name: (systemd-services.yml) Check if Service is disabled (Debian based OS)
  shell: 'systemctl list-unit-files | grep -e "^{{ item.item }}.service"  | grep -q "disabled";'
  register: service_is_enabled
  changed_when: "service_is_enabled.rc == 0"
  failed_when: "service_is_enabled.rc > 1"
  with_items: 
    - "{{ service_exists.results }}"
  loop_control:
    label: '{{ item.item }}'
  when: 
    - item.rc == 0 

#- debug: msg="{{ service_is_enabled.results }}"

- name: (systemd-services.yml) Enable service
  systemd:
    name: "{{ item.item.item }}.service"
    enabled: true
  with_items:
    - "{{ service_is_enabled.results }}"
  loop_control:
    label: '{{ item.item.item }}'
  when:
    - item.changed

- name: (systemd-services.yml) Check if Service is active
  shell: 'systemctl is-active {{ item.item }}.service'
  register: service_is_active
  changed_when: 'service_is_active.stdout == "inactive"'
  failed_when: 'service_is_active.rc > 3'
  with_items:
    - "{{ service_exists.results }}"
  loop_control:
    label: '{{ item.item }}'
  when:
    - item.rc == 0



- name: (systemd-services.yml) Start service
  systemd:
    name: "{{ item.item.item }}.service"
    state: started
  with_items:
    - "{{ service_is_active.results }}"
  loop_control:
    label: '{{ item.item.item }}'
  when:
    - item.changed
