---

- when: postgres_pgdg_repo
  block:
    - name: Install pgdg apt repo key
      apt_key:
        url: https://www.postgresql.org/media/keys/ACCC4CF8.asc
        state: present
    - name: Configure pgdg apt repo
      apt_repository:
        repo: >-
          deb
          https://apt.postgresql.org/pub/repos/apt
          {{ ansible_distribution_release }}-pgdg
          main

- name: ensure postgres packages are installed
  apt:
    name:
      # yamllint disable-line rule:line-length
      - postgresql{{ "-{}".format(postgres_version) if postgres_version is defined }}
      - python3-psycopg2
      - libpq-dev
    state: present

- name: ensure legacy postgres packages are installed
  apt:
    name:
      - python-psycopg2
    state: present
  when: ansible_distribution_major_version|int(default=99) < 11

- name: ensure postgres is started
  service:
    name: postgresql
    state: started
    enabled: true

- name: configure snapshots
  when: '{{postgres_rsnapshot}}'
  block:
    - name: ensure we have our postgres backup script
      copy:
        src: "pgbackup{{ '-bullseye' if ansible_distribution_major_version|int(default=99) > 10 else '' }}.sh"
        dest: /usr/local/bin/pgbackup.sh
        owner: root
        group: root
        mode: '0755'

    - name: ensure we have our rsnapshot config
      copy:
        src: rsnapshot.conf
        dest: /etc/rsnapshot.d/postgres.conf
        owner: root
        group: root
        mode: '0644'

    - name: remove obsolete crontab
      file:
        path: /etc/cron.d/postgres-snapshot
        state: absent
