---
-
  name: Set PostgreSQL environment variables.
  ansible.builtin.template:
    src: postgres.sh.j2
    dest: /etc/profile.d/postgres.sh
    mode: "0644"
  notify: Restart postgresql

-
  name: Ensure PostgreSQL data directory exists.
  ansible.builtin.file:
    path: "{{ postgresql_data_dir }}"
    owner: "{{ postgresql_user }}"
    group: "{{ postgresql_group }}"
    state: directory
    mode: "0700"

-
  name: Check if PostgreSQL database is initialized.
  ansible.builtin.stat:
    path: "{{ postgresql_data_dir }}/PG_VERSION"
  register: pgdata_dir_version

-
  name: Ensure PostgreSQL database is initialized.
  ansible.builtin.command: "{{ postgresql_bin_path }}/initdb -D {{ postgresql_data_dir }}"
  when: not pgdata_dir_version.stat.exists
  changed_when: false
  become: true
  become_user: "{{ postgresql_user }}"
  # See: https://github.com/ansible/ansible/issues/16048#issuecomment-229012509
  vars:
    ansible_ssh_pipelining: true

-
  name: Ensure PostgreSQL log directory exists.
  ansible.builtin.file:
    path: "{{ postgresql_effective_log_dir }}"
    owner: "{{ postgresql_user }}"
    group: "{{ postgresql_group }}"
    state: directory
    mode: "0700"
