# Copyright 2018-2023 Chris Croome
#
# This file is part of the Webarchitects Apache Ansible role.
#
# The Webarchitects Apache Ansible role is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# The Webarchitects Apache Ansible role is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with the Webarchitects Apache Ansible role. If not, see <https://www.gnu.org/licenses/>.
---
- name: Apache sites checked
  block:

    - name: Check loaded sites
      block:

        - name: Register the loaded sites
          ansible.builtin.command: a2query -s
          check_mode: false
          changed_when: false
          register: apache_sites_check

      rescue:

        - name: No sites enabled
          ansible.builtin.set_fact:
            apache_sites_loaded: []
          when: ( "No site matches" in apache_sites_check.stderr )

    - name: Set an array of loaded Apache sites
      block:

        - name: Debug the loaded sites
          ansible.builtin.debug:
            var: apache_sites_check.stdout_lines
            verbosity: 2

        - name: Set apache_sites_loaded to an empty array
          ansible.builtin.set_fact:
            apache_sites_loaded: []

        - name: Set an array of the loaded sites
          ansible.builtin.set_fact:
            apache_sites_loaded: "{{ apache_sites_loaded | default([]) + [line.split(' ')[0]] }}"
          when: apache_sites_check.stdout is defined
          loop: "{{ apache_sites_check.stdout_lines }}"
          loop_control:
            loop_var: line
            label: "{{ line }}"

      when:
        - apache_sites_check.stdout is defined
        - apache_sites_check.stderr | length == 0

    - name: Debug loaded sites
      ansible.builtin.debug:
        var: apache_sites_loaded
        verbosity: 1

  tags:
    - apache
...
