---
- name: Open firewall for PGDG repository
  ansible.builtin.replace:
    name: /etc/default/minifirewall
    regexp: "^(HTTPSITES='((?!apt\\.postgresql\\.org|0\\.0\\.0\\.0).)*)'$"
    replace: "\\1 apt.postgresql.org'"
  notify: Restart minifirewall

- ansible.builtin.meta: flush_handlers

- name: "Ensure {{ apt_keyring_dir }} directory exists"
  file:
    path: "{{ apt_keyring_dir }}"
    state: directory
    mode: "755"
    owner: root
    group: root

- name: Add PGDG GPG key
  ansible.builtin.copy:
    src: postgresql.asc
    dest: "{{ apt_keyring_dir }}/postgresql.asc"
    force: true
    mode: "0644"
    owner: root
    group: root

- name: Add PGDG repository (Debian <12)
  ansible.builtin.apt_repository:
    repo: "deb [signed-by={{ apt_keyring_dir }}/postgresql.asc] http://apt.postgresql.org/pub/repos/apt/ {{ ansible_distribution_release }}-pgdg main"
    filename: postgresql
    update_cache: yes
  when: ansible_distribution_major_version is version('12', '<')

- name: Add PGDG repository (Debian >=12)
  ansible.builtin.template:
    src: postgresql.sources.j2
    dest: /etc/apt/sources.list.d/postgresql.sources
  register: postgresql_sources
  when: ansible_distribution_major_version is version('12', '>=')

- name: Update APT cache
  ansible.builtin.apt:
    update_cache: yes
  when: postgresql_sources is changed

- name: Add APT preference file
  ansible.builtin.template:
    src: postgresql.pref.j2
    dest: /etc/apt/preferences.d/postgresql.pref
    mode: "0644"
