- name: Ensure directory for postgresql repo key exists
  ansible.builtin.file:
    path: "{{ postgresql_repo_key_dir }}"
    state: directory
    mode: "0755"
  become: true
- name: Add postgresql repo key
  ansible.builtin.get_url:
    url: https://www.postgresql.org/media/keys/ACCC4CF8.asc
    dest: "{{ postgresql_repo_key_file }}"
    mode: "0644"
  become: true

- name: Add postgresql repo into sources list
  ansible.builtin.apt_repository:
    repo: deb [signed-by={{ postgresql_repo_key_file }}] https://apt.postgresql.org/pub/repos/apt {{ ansible_distribution_release }}-pgdg main
    state: present
  become: true

- name: Install postgresql
  ansible.builtin.apt:
    pkg:
      - postgresql-16
      - python3-psycopg
    state: present
    update_cache: true
  become: true

- name: Check out if postgresql is initialized
  ansible.builtin.stat:
    path: "{{ postgresql_data_dir }}"
  register: postgresql_data_stat
  become: true

- name: Initialize postgresql
  ansible.builtin.command: "{{ postgresql_bin_initdb }} -D {{ postgresql_data_dir }}"
  when: not postgresql_data_stat.stat.exists
  changed_when: true

- name: Replace everything with a new set of rules
  community.postgresql.postgresql_pg_hba:
    dest: "{{ postgresql_conf_pg_hba }}"
    overwrite: true # remove pre-existing rules

    # defaults
    rules_behavior: combine
    contype: hostssl
    users: all
    databases: all
    method: scram-sha-256

    rules:
      - contype: local
        users: postgres
        method: trust
      - contype: hostssl
        address: "0.0.0.0/0"
      - contype: hostssl
        address: "::/0"
  become: true
  register: pg_hba_reg

- name: Restart postgresql on pg_hba change
  ansible.builtin.systemd_service:
    state: restarted
    name: postgresql
  when: pg_hba_reg.changed # noqa: no-handler TODO can we add a handler here?
  become: true

- name: Start postgresql
  ansible.builtin.systemd_service:
    state: started
    name: postgresql
  become: true

- name: Set parameters
  community.postgresql.postgresql_set:
    login_unix_socket: /var/run/postgresql
    login_user: postgres
    name: "{{ item.name }}"
    value: "{{ item.value }}"
  loop: "{{ postgresql_set_vars | dict2items(key_name='name', value_name='value') }}"
  register: set

- name: Restart postgresql
  ansible.builtin.systemd_service:
    state: restarted
    name: postgresql
  when: set.results | postgresql_restart_required
  become: true