---
- name: Setting Web Server Facts
  ansible.builtin.set_fact:
    zabbix_web_user: "{{ zabbix_web_user if zabbix_web_user is defined else _apache_user }}"
    zabbix_web_group: "{{ zabbix_web_group if zabbix_web_group is defined else _apache_group }}"
    zabbix_web_vhost_location: "{{ zabbix_web_vhost_location if zabbix_web_vhost_location is defined else _apache_vhost_location }}"
  tags:
    - always

- name: "Apache | Installing Zabbix Apache Conf"
  package:
    name: "{{ _zabbix_web_apache_packages + _zabbix_web_apache_php_dependencies | default([]) }}"
    state: "{{ zabbix_web_package_state }}"
    update_cache: true
    disablerepo: "{{ zabbix_web_disable_repo | default(_zabbix_web_disable_repo | default(omit)) }}"
  environment:
    http_proxy: "{{ zabbix_http_proxy | default(None) | default(omit) }}"
    https_proxy: "{{ zabbix_https_proxy | default(None) | default(omit) }}"
  register: zabbix_apache_conf_install
  until: zabbix_apache_conf_install is succeeded
  become: true
  tags:
    - install
    - dependencies
    - database

- name: "Apache | Get Apache version"
  ansible.builtin.shell: |
    PATH=/usr/sbin:$PATH
    set -o pipefail
    apachectl -v | grep 'version' | awk -F '/' '{ print $2 }'| awk '{ print $1 }' | cut -c 1-3
  changed_when: false
  register: apachectl_version
  check_mode: false
  args:
    executable: /bin/bash
  tags:
    - config

- name: "Apache | Set correct apache_version"
  ansible.builtin.set_fact:
    apache_version: "{{ apachectl_version.stdout }}"
  tags:
    - config

- name: "Apache | Install apache vhost"
  ansible.builtin.template:
    src: apache_vhost.conf.j2
    dest: "{{ zabbix_web_vhost_location }}"
    owner: "{{ zabbix_web_user }}"
    group: "{{ zabbix_web_group }}"
    mode: 0644
  when: zabbix_web_create_vhost
  become: true
  notify:
    - restart apache
  tags:
    - config

- name: "Apache | Enable Site (Debian Only)"
  ansible.builtin.file:
    src: "{{ zabbix_web_vhost_location }}"
    dest: /etc/apache2/sites-enabled/zabbix.conf
    state: link
    owner: "{{ zabbix_web_user }}"
    group: "{{ zabbix_web_group }}"
    mode: 0644
  become: true
  when: ansible_facts['os_family'] == 'Debian' and zabbix_web_create_vhost
  tags:
    - config
