---
- name: Vérification de la présence des paramètres d'entrées dans les variables
  ansible.builtin.fail:
    msg: |
      La variable {{ item }} est obligatoire pour utiliser le role.
      Veuillez la renseigner dans le dossier host_vars.
  when:
    - item is not defined
  loop:
    - db_user
    - db_password
    - db_name

- name: Apt Update and Install Postgres
  ansible.builtin.apt:
    update_cache: true
    name:
      - postgresql
      - acl
      - python3-psycopg2
    state: present
  when: ansible_pkg_mgr == "apt"

- name: Yum Update and Install Postgres
  ansible.builtin.yum:
    update_cache: true
    name:
      - postgresql
      - postgresql-server
      - postgresql-contrib
      - acl
      - python3-psycopg2
    state: present
  when: ansible_pkg_mgr == "yum"

- name: Dnf Update and Install Postgres
  ansible.builtin.dnf:
    update_cache: true
    name:
      - postgresql
      - postgresql-server
      - postgresql-contrib
      - acl
      - python3-psycopg2
    state: present
  when: ansible_pkg_mgr == "dnf"

- name: Yum/Dnf management
  when: ansible_pkg_mgr == "dnf" or ansible_pkg_mgr == "yum"
  block:
    - name: Find out if PostgreSQL is initialized
      ansible.builtin.stat:
        path: "/var/lib/pgsql/data/pg_hba.conf"
      register: postgres_data

    - name: Init database only for Yum/Dnf OS
      ansible.builtin.command: /usr/bin/postgresql-setup --initdb
      when: not postgres_data.stat.exists

- name: Start and enable services
  ansible.builtin.service:
    name: postgresql
    state: started
    enabled: true

- name: Create db user
  community.postgresql.postgresql_user:
    state: present
    name: "{{ db_user }}"
    password: "{{ db_password }}"
    role_attr_flags: CREATEDB
  become: true
  become_user: postgres

- name: Allow md5 connection for the db user
  community.postgresql.postgresql_pg_hba:
    dest: "/etc/postgresql/12/main/pg_hba.conf"
    contype: host
    databases: all
    method: md5
    users: "{{ db_user }}"
    create: true
  become: true
  become_user: postgres
  notify: Restart postgres
  when: ansible_pkg_mgr == "apt"

- name: Allow md5 connection for the db user
  community.postgresql.postgresql_pg_hba:
    dest: "~/data/pg_hba.conf"
    contype: host
    databases: all
    method: md5
    users: "{{ db_user }}"
    create: true
  become: true
  become_user: postgres
  notify: Restart postgres
  when: ansible_pkg_mgr == "dnf" or ansible_pkg_mgr == "yum"
