---
- name: Install PostgreSQL
  pacman: name=postgresql state=present

- name: Install psycopg2
  pacman: name=python2-psycopg2 state=present

- name: Create postgres data root
  file: path={{ postgresql.root }}/data state=directory owner=postgres group=postgres

- name: Initialize database cluster
  command: initdb --locale en_US.UTF-8 -E UTF8 -D {{ postgresql.root }}/data creates={{ postgresql.root }}/data/postgresql.conf
  become: yes
  become_user: postgres

- name: Disable synchronous commits
  lineinfile: dest={{ postgresql.root }}/data/postgresql.conf
              regexp=^synchronous_commit
              state=present
              line="synchronous_commit = off"
  notify:
    - restart postgresql

- name: Prevent disk writes when idle
  lineinfile: dest={{ postgresql.root }}/data/postgresql.conf
              regexp=^stats_temp_directory
              state=present
              line="stats_temp_directory = '/run/postgresql'"
  notify:
    - restart postgresql

- name: Create service override directory
  file: path=/etc/systemd/system/postgresql.service.d state=directory

- name: Push service override file
  template: src=postgresql-override.conf.j2 dest=/etc/systemd/system/postgresql.service.d/override.conf
  notify:
    - reload systemd config
    - restart postgresql

- name: Disable and stop PostgreSQL
  service: name=postgresql.service enabled=no state=stopped
  when: postgresql is not defined or postgresql.enable is not defined or postgresql.enable != True

- name: Enable and start PostgreSQL
  service: name=postgresql.service enabled=yes state=started
  when: postgresql is defined and postgresql.enable is defined and postgresql.enable == True

- name: Create the PostgreSQL user
  postgresql_user: name={{ user.name }} role_attr_flags=CREATEDB,NOSUPERUSER
  when: postgresql is defined and postgresql.enable is defined and postgresql.enable == True
