---
- name: "Delete package <prometheus postgres exporter>"
  apt:
    name: "prometheus-postgres-exporter"
    state: absent

- name: "Check if version is already installed"
  ansible.builtin.stat:
    path: "{{ postgres_exporter_dir }}/{{ postgres_exporter_dist }}/postgres_exporter"
  register: check_pg_exp

- name: "Download and extract pg_exporter"
  unarchive:
    src: "{{ postgres_exporter_download_url }}"
    dest: "{{ postgres_exporter_dir }}"
    owner: root
    group: root
    mode: "u=rwx,g=rx,o=rx"
    remote_src: true
    creates: "{{ postgres_exporter_dir }}/{{ postgres_exporter_dist }}/postgres_exporter"
  when:
    - not check_pg_exp.stat.exists

- name: "Create systemd service file"
  become: true
  template:
    src: "postgres_exporter.systemd.j2"
    dest: "/etc/systemd/system/postgres_exporter.service"
    owner: root
    group: root
    mode: "u=rw,go=r"
  notify:
    - restart postgres_exporter

- name: "Create Config for postgres_exporter"
  template:
    src: "postgres_exporter.default.conf.j2"
    dest: "/etc/default/postgres_exporter"
    owner: root
    group: "{{ postgres_exporter_group }}"
    mode: "u=rw,g=r,o="
  notify: restart postgres_exporter

- name: "Create file for additional queries"
  copy:
    dest: '{{ postgres_exporter_home }}/queries.yml'
    owner: root
    group: '{{ postgres_exporter_group }}'
    mode: '0644'
    content: "{{ lookup('vars','postgres_exporter_additional_queries') | to_nice_yaml }}"
  notify: restart postgres_exporter

- name: "Ensure postgres_exporter up and running"
  service:
    name: postgres_exporter
    state: started
    enabled: yes
    daemon_reload: yes

- name: Check role prometheus exists # noqa command-instead-of-shell no-changed-when
  become: yes
  become_user: postgres
  shell: "/usr/bin/psql -Atc \"SELECT count(rolname) FROM pg_roles where rolname='prometheus'\""
  register: role_check
  ignore_errors: yes

- name: "Copy prometheus_postgres_exporter init script"
  copy:
    src: init.sql
    dest: /tmp/prometheus_postgres_exporter.sql
    mode: '0755'
  when: "role_check.stdout == '0' and server_type == 'master'"

- name: "Execute prometheus_postgres_exporter init script" # noqa command-instead-of-shell
  become: true
  become_user: postgres
  shell: "psql -f /tmp/prometheus_postgres_exporter.sql"
  when: "role_check.stdout == '0' and server_type == 'master'"

- name: "Delete prometheus_postgres_exporter init script"
  file: path="/tmp/prometheus_postgres_exporter.sql" state=absent
  when: "role_check.stdout == '0' and server_type == 'master'"
