---

- name: server status dirname exists
  file:
    dest: "{{ apache_serverstatus_suffix_file | dirname }}"
    mode: "0700"
    owner: root
    group: root
    state: directory

- name: set apache serverstatus suffix if provided
  copy:
    dest: "{{ apache_serverstatus_suffix_file }}"
    # The last character "\u000A" is a line feed (LF), it's better to keep it
    content: "{{ apache_serverstatus_suffix }}\u000A"
    force: yes
  when: apache_serverstatus_suffix != ""

- name: generate random string for server-status suffix
  shell: "apg -a 1 -M N -n 1 > {{ apache_serverstatus_suffix_file }}"
  args:
    creates: "{{ apache_serverstatus_suffix_file }}"

- name: read apache server status suffix
  command: "tail -n 1 {{ apache_serverstatus_suffix_file }}"
  changed_when: False
  check_mode: no
  register: new_apache_serverstatus_suffix

- name: overwrite apache_serverstatus_suffix
  set_fact:
    apache_serverstatus_suffix: "{{ new_apache_serverstatus_suffix.stdout }}"

- debug:
    var: apache_serverstatus_suffix

- name: replace server-status suffix in default site index
  replace:
    dest: /var/www/index.html
    regexp: '__SERVERSTATUS_SUFFIX__'
    replace: "{{ apache_serverstatus_suffix }}"

- name: add server-status suffix in default site index if missing
  replace:
    dest: /var/www/index.html
    regexp: '"/server-status-?"'
    replace: '"/server-status-{{ apache_serverstatus_suffix }}"'

- name: add server-status suffix in default VHost
  replace:
    dest: /etc/apache2/sites-available/000-evolinux-default.conf
    regexp: '<Location /server-status-?>'
    replace: '<Location /server-status-{{ apache_serverstatus_suffix }}>'
  notify: reload apache

- name: Munin configuration has a section for apache
  lineinfile:
    dest: /etc/munin/plugin-conf.d/munin-node
    line: "[apache_*]"
    create: no

- name: apache-status URL is configured for Munin
  lineinfile:
    dest: /etc/munin/plugin-conf.d/munin-node
    line: "env.url http://{{ apache_serverstatus_host }}/server-status-{{ apache_serverstatus_suffix }}?auto"
    regexp: 'env.url http://[^\\/]+/server-status'
    insertafter: "[apache_*]"
    create: no
  notify: restart munin-node
