---
- include: preflight.yml

- name: Create the Apache Exporter group
  become: true
  group:
    name: "{{ __apache_exporter_group }}"
    state: present
    system: true

- name: Create the Apache Exporter user
  become: true
  user:
    name: "{{ __apache_exporter_user }}"
    groups: "{{ __apache_exporter_group }}"
    append: true
    shell: /usr/sbin/nologin
    system: true
    createhome: false
    home: /

- name: Distribution Directory
  become: true
  become_user: root
  file:
    path: "{{ prometheus_exporter_dir }}"
    owner: root
    group: root
    mode: "u=rwx,go=rx"
    state: directory

- name: download tarball
  become: true
  become_user: root
  ignore_errors: yes
  get_url:
    url: "https://github.com/Lusitaniae/apache_exporter/releases/download/v{{ apache_exporter_version }}/apache_exporter-{{ apache_exporter_version }}.linux-{{ go_arch_map[ansible_architecture] | default(ansible_architecture) }}.tar.gz"
    dest: "{{ prometheus_exporter_dist_dir }}/{{ apache_exporter_signature }}.tar.gz"
    owner: root
    group: root
    mode: "u=rwx,go=rx"
  register: _download_binary
  until: _download_binary is succeeded
  retries: 5
  delay: 2

- name: make distribution directory
  become: true
  become_user: root
  file:
    path: "{{ apache_exporter_dist_dir }}"
    owner: root
    group: root
    mode: "u=rwx,go=rx"
    state: directory

- name: untar tarball
  become: true
  become_user: root
  unarchive:
    src: "{{ prometheus_exporter_dist_dir }}/{{ apache_exporter_signature }}.tar.gz"
    dest: "{{ prometheus_exporter_dist_dir }}"
    remote_src: true
    owner: root
    group: root
    mode: "u=rwx,go=rx"
    creates: "{{ apache_exporter_dist_dir }}/apache-prometheus-exporter"

- name: symlink
  become: true
  become_user: root
  file:
    src: "{{ apache_exporter_dist_dir }}/apache_exporter"
    path: "{{ prometheus_exporter_dir }}/apache_exporter"
    owner: root
    group: root
    force: true
    state: link
  notify: restart apache exporter

- name: Copy the apache_exporter systemd service file
  become: true
  template:
    src: apache_exporter.service.j2
    dest: /etc/systemd/system/apache_exporter.service
    owner: root
    group: root
    mode: 0644
  no_log: true
  notify:
    - restart apache exporter

- name: Ensure apache_exporter is enabled on boot
  become: true
  systemd:
    name: apache_exporter
    state: started
    enabled: true
