# 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 disabled and enabled
  block:

    - name: Apache sites disabled
      ansible.builtin.command: "a2dissite {{ apache_site }}"
      args:
        removes: "/etc/apache2/sites-enabled/{{ apache_site }}.conf"
      when:
        - apache_sites_disabled is defined
        - apache_sites_disabled != []
        - apache_site in ansible_local.a2query.sites_enabled
      loop: "{{ apache_sites_disabled }}"
      loop_control:
        loop_var: apache_site
        label: "{{ apache_site }}"

    - name: Check that all the sites to be enabled exist
      ansible.builtin.stat:
        path: "/etc/apache2/sites-available/{{ apache_site }}.conf"
      when: apache_site not in ansible_local.a2query.sites_enabled
      register: apache_site_path
      failed_when:
        - not ansible_check_mode | bool
        - not apache_site_path.stat.exists | bool
      loop: "{{ apache_sites_enabled }}"
      loop_control:
        loop_var: apache_site
        label: "{{ apache_site }}"

    - name: Apache sites enabled
      ansible.builtin.command: "a2ensite {{ apache_site }}"
      args:
        creates: "/etc/apache2/sites-enabled/{{ apache_site }}.conf"
      when:
        - apache_sites_enabled is defined
        - apache_sites_enabled != []
        - apache_site not in ansible_local.a2query.sites_enabled
      loop: "{{ apache_sites_enabled }}"
      loop_control:
        loop_var: apache_site
        label: "{{ apache_site }}"

  tags:
    - apache
...