---

- name: "Creating backup directory <{{ backup_directory }}>"
  ansible.builtin.file:
    path: "{{ backup_directory }}"
    state: directory
    owner: "postgres"
    group: "postgres"
    mode: '0755'


- name: "Restore database ... "
  block:
  - name: "Restore | DROP database with suffix <{{ custom_backup_name }}>"
    community.postgresql.postgresql_db:
      name: "{{ item.name }}"
      state: absent
      force: true
    loop: "{{ postgres_acls }}"
    become_user: postgres
    become: true

  - name: "Restore | RECREATE database with suffix <{{ custom_backup_name }}>"
    community.postgresql.postgresql_db:
      name: "{{ item.name }}"
      force: true
    loop: "{{ postgres_acls }}"
    become_user: postgres
    become: true

  when:
    - database_backup_state is defined
    - database_backup_state in ['restore']

- name: "Handle backup state <{{ database_backup_state }}> with suffix <{{ custom_backup_name }}>"
  community.postgresql.postgresql_db:
    name: "{{ item.name }}"
    state: "{{ database_backup_state }}"
    target: "{{ backup_directory }}/{{ item.name }}__{{ custom_backup_name }}.sql.gz"
  loop: "{{ postgres_acls }}"
  become_user: postgres
  become: true
