---

- name: Install postgresql
  ansible.builtin.apt:
    pkg:
      - postgresql
      - python3-psycopg2
    update_cache: true
  become: true
  notify: Restart postgres

- name: Create databases
  community.postgresql.postgresql_db:
    name: "{{ item.database }}"
  become: true
  become_user: postgres
  loop: "{{ postgres_users }}"

- name: Create postgres user
  community.postgresql.postgresql_user:
    db: "{{ item.database }}"
    name: "{{ item.user }}"
    password: "{{ item.password }}"
  become: true
  become_user: postgres
  loop: "{{ postgres_users }}"

- name: Set database owners
  community.postgresql.postgresql_db:
    name: "{{ item.database }}"
    owner: "{{ item.user }}"
  become: true
  become_user: postgres
  loop: "{{ postgres_users }}"

- name: Copy authorization config
  ansible.builtin.copy:
    src: pg_hba.conf
    dest: /etc/postgresql/16/main/pg_hba.conf
    owner: postgres
    group: postgres
    mode: "0640"
  become: true
  notify: Restart postgres

- name: Copy connection config
  ansible.builtin.copy:
    src: postgresql.conf
    dest: /etc/postgresql/16/main/postgresql.conf
    owner: postgres
    group: postgres
    mode: "0640"
    backup: true
  become: true
  notify: Restart postgres
