---
- name: Set postgresql installation directory
  ansible.builtin.set_fact:
    postgres_dir: /etc/postgresql/{{ postgres.version }}/main

- name: Install postgresql
  ansible.builtin.apt:
    update_cache: true
    name: postgresql
    state: present
  register: apt_result
  retries: 3
  until: apt_result is succeeded

- name: Ensure main postgresql directory exists
  ansible.builtin.file:
    path: "{{ postgres_dir }}"
    state: directory
    owner: postgres
    group: postgres
    mode: 0755

- name: Ensure configuration directory exists
  ansible.builtin.file:
    path: "{{ postgres_dir }}/conf.d"
    state: directory
    owner: postgres
    group: postgres
    mode: 0755

- name: Configuration of postgresql {{ postgres.version }}
  ansible.builtin.template:
    src: postgresql/postgresql.conf.j2
    dest: "{{ postgres_dir }}/postgresql.conf"
    mode: 0640
    owner: postgres
    group: postgres
  notify:
    - reload postgresql

- name: Master of configuration of postgresql {{ postgres.version }}
  ansible.builtin.template:
    src: postgresql/{{ item }}.j2
    dest: "{{ postgres_dir }}/{{ item }}"
    mode: 0640
    owner: postgres
    group: postgres
  loop:
    - pg_hba.conf
    - pg_ident.conf
  notify:
    - reload postgresql
  when: not(postgres.replica | default(False))

- name: Create backup directory
  ansible.builtin.file:
    path: "{{ postgres.backup.dir }}"
    owner: postgres
    group: postgres
    state: directory
    mode: 0770
  when: postgres.backup is defined

- name: Create backup cron
  ansible.builtin.template:
    src: cron.d/pg_dump.j2
    dest: /etc/cron.d/pg_dump
  when: postgres.backup is defined