---
- name: Install and configure Apache
  block:

    - name: Apache present from buster-backports
      apt:
        pkg:
          - apache2
        state: latest
        install_recommends: true
        default_release: buster-backports
        update_cache: true
      when: ansible_distribution_release is regex('^buster$')

    - name: Apache present
      apt:
        pkg:
          - apache2
        state: present
        install_recommends: true
        update_cache: false
      when: ansible_distribution_release is not regex('^buster$')

    - name: Additional packages present
      apt:
        pkg: "{{ apache_packages_present }}"
        state: present
        update_cache: false
      when: ( apache_packages_present is defined ) and ( apache_packages_present != [] )

    - name: Include Apache checks
      include_tasks: checks.yml

    - name: Apache DocumentRoot present
      file:
        path: "{{ apache_document_root }}"
        state: directory
        mode: 0755
        owner: root
        group: root

    - name: Apache DH parameters file present
      openssl_dhparam:
        path: "{{ apache_dhparam_path }}"
        size: "{{ apache_dhparam_size }}"

    - name: Include MPM switching tasks
      include_tasks: mpm.yml
      when: ( apache_mpm_loaded not in apache_mods_enabled ) or ( apache_mpm_loaded | length == 0 )

    - name: Apache config available
      include_tasks: config.yml

    - name: Apache envars in place
      template:
        src: templates/envvars.j2
        dest: /etc/apache2/envvars
        mode: 0755
        owner: root
        group: root

    - name: Apache modules disabled and enabled
      include_tasks: a2mod.yml
      when: ( apache_mods_disabled is defined ) or ( apache_mods_enabled is defined )

    - name: Apache conf disabled and enabled
      include_tasks: a2conf.yml
      when: ( apache_sites_disabled is defined ) or ( apache_conf_enabled is defined )

    - name: Apache sites disabled and enabled
      include_tasks: a2site.yml
      when: ( apache_sites_disabled is defined ) or ( apache_sites_enabled is defined )

    - name: Apache enabled for systemd servers
      systemd:
        name: apache2
        enabled: true
      when: ansible_distribution_release is regex('^buster|bullseye$')

    - name: Apache configtest
      command: apache2ctl configtest
      register: apache_configtest
      changed_when: '"Syntax OK" not in apache_configtest.stderr'
      check_mode: false

    - debug:
        msg: "{{ apache_configtest.stderr }}"
        verbosity: 1

    - name: Fail if Apache configtest is not OK
      fail:
        msg: "{{ apache2ctl_configtest.stdout }}"
      when: '"Syntax OK" not in apache_configtest.stderr'

    - name: Apache restarted
      service:
        name: apache2
        state: restarted
      when: '"Syntax OK" in apache_configtest.stderr'

  tags:
    - apache
...
