- name: Define OS-specific variables
  include_vars: "{{ ansible_os_family }}.yml"

- name: Install prerequisite packages
  include_tasks: "{{ ansible_os_family }}.yml"

- name: Set PostgreSQL environment variables
  become: yes
  template:
    src: postgres.sh.j2
    dest: /etc/profile.d/postgres.sh
    mode: 0644
  notify: restart postgresql

- name: Ensure PostgreSQL data directory exists
  become: yes
  become_user: postgres
  file:
    path: "{{ postgresql_data_dir }}"
    owner: postgres
    group: postgres
    state: directory
    mode: 0700

- name: Initialize PostgreSQL database cluster
  become: yes
  become_user: postgres
  command: "{{ postgresql_bin_path }}/initdb -D {{ postgresql_data_dir }}"
  args:
    creates: "{{ postgresql_data_dir }}/PG_VERSION"
  environment:
    LC_ALL: "{{ postgres_locale }}"

- name: Check FIPS status
  command: cat /proc/sys/crypto/fips_enabled
  register: _fips_enabled
  ignore_errors: true
  changed_when: false

- name: Setup postgres configuration files
  become: yes
  become_user: postgres
  template:
    src: "{{ item }}.j2"
    dest: "{{ postgresql_config_path }}/{{ item }}"
    owner: postgres
    group: postgres
    mode: 0644
  loop:
    - pg_hba.conf
    - postgresql.conf
  notify: restart postgresql

- name: Ensure PostgreSQL is started and enabled on boot
  become: yes
  systemd:
    name: "{{ postgresql_daemon }}"
    state: started
    enabled: yes

- name: Hold until Postgresql is up and running
  wait_for:
    port: "{{ postgres_port }}"
    timeout: 120
    sleep: 10

- name: Create user
  become: yes
  become_user: postgres
  postgresql_user:
    name: "{{ curr_user.username }}"
    password: "{{ curr_user.password }}"
    conn_limit: "-1"
  loop: "{{ database | dict2items | map(attribute='value') | list }}"
  loop_control:
    loop_var: curr_user
  when: curr_user.enabled | bool
  no_log: true  # secret passwords

- name: Create database
  become: yes
  become_user: postgres
  postgresql_db:
    name: "{{ curr_db.name }}"
    owner: "{{ curr_db.owner }}"
    encoding: UTF-8
    lc_collate: "{{ postgres_locale }}"
    lc_ctype: "{{ postgres_locale }}"
    template: template0
  loop: "{{ database | dict2items | map(attribute='value') | list }}"
  loop_control:
    loop_var: curr_db
  when: curr_db.enabled | bool
  no_log: true  # secret passwords

- name: Grant privs on db
  become: yes
  become_user: postgres
  postgresql_privs:
    database: "{{ curr_db.name }}"
    role: "{{ curr_db.owner }}"
    state: present
    privs: ALL
    type: database
  loop: "{{ database | dict2items | map(attribute='value') | list }}"
  loop_control:
    loop_var: curr_db
  when: curr_db.enabled | bool
  no_log: true  # secret passwords
