---
- name: define distribution-specific variables
  include_vars: "{{ ansible_os_family }}.yml"

- name: create directory for bind mount if necessary
  file:
    path: "{{ postgres_server_bind_mount_var_lib_pgsql_target }}"
    state: directory
  become: yes
  when: postgres_server_bind_mount_var_lib_pgsql


- name: perform bind mount if necessary
  mount:
    path: "/var/lib/pgsql"
    src: "{{ postgres_server_bind_mount_var_lib_pgsql_target }}"
    opts: bind
    state: mounted
    fstype: none
  become: yes
  when: postgres_server_bind_mount_var_lib_pgsql

- name: perform installation
  include_tasks: "{{ ansible_os_family }}.yml"

- name: extend path
  copy:
    dest: /etc/profile.d/postgres-path.sh
    mode: a=rx
    content: "export PATH=$PATH:/usr/pgsql-{{ postgres_server_version }}/bin"
  become: yes

- name: initialize PostgreSQL database cluster
  environment:
    LC_ALL: "en_US.UTF-8"
  vars:
    ansible_become: "{{ postgres_server_initdb_become }}"
    ansible_become_user: "{{ postgres_server_user }}"
  command: "{{ postgres_server_cmd_initdb }} {{ postgres_server_data_location }}"
  args:
    creates: "{{ postgres_server_data_location }}/PG_VERSION"

- name: install postgres configuration
  template:
    src: "{{ item }}.j2"
    dest: "{{ postgres_server_config_location }}/{{ item }}"
    owner: postgres
    group: postgres
    mode: u=rw,go=r
  vars:
    ansible_become: "{{ postgres_server_initdb_become }}"
    ansible_become_user: "{{ postgres_server_user }}"
  loop:
    - pg_hba.conf
    - postgresql.conf

- name: enable postgres service
  systemd:
    name: "{{ postgres_server_service_name }}"
    state: started
    enabled: yes
  become: yes

- name: Hold until Postgresql is up and running
  wait_for:
    port: 5432

- name: Create users
  become_user: postgres
  become: yes
  postgresql_user:
    name: "{{ item.db_user }}"
    password: "{{ item.db_password }}"
    conn_limit: "-1"
  loop: "{{ db_users|default([]) }}"
  no_log: true  # secret passwords

- name: Create a database
  become_user: postgres
  become: yes
  postgresql_db:
    name: "{{ item.db_name }}"
    owner: "{{ item.db_owner }}"
    encoding: UTF-8
  loop: "{{ dbs|default([]) }}"

- name: Grant privs on db
  become_user: postgres
  become: yes
  postgresql_privs:
    database: "{{ item.db_name }}"
    role: "{{ item.db_owner }}"
    state: present
    privs: ALL
    type: database
  loop: "{{ dbs|default([]) }}"

- name: restart postgres
  service:
    name: "{{ postgres_server_service_name }}"
    state: restarted
  become: yes

- debug:
    msg: "Restarted postgres service {{ postgres_server_service_name }}"