---
- name: Install the pgpool package
  apt: name={{ item }} state={{ psql_pgpool_pkg_state }}
  with_items: '{{ pgpool_pkgs }}'
  tags: [ 'postgresql', 'postgres', 'pgpool' ]

- name: Configure pcp
  template: src=pcp.conf.j2 dest=/etc/pgpool2/pcp.conf owner=root group=postgres mode=0640
  tags: [ 'postgresql', 'postgres', 'pgpool', 'pcp_conf', 'pgpool_conf' ]
  
- name: Install the pgpool configuration file
  template: src=pgpool.conf.j2 dest=/etc/pgpool2/pgpool.conf owner=root group=postgres mode=0640
  notify: Restart pgpool2
  tags: [ 'postgresql', 'postgres', 'pgpool', 'pgpool_conf' ]

- name: Give access to the remote postgresql clients
  lineinfile: name=/etc/pgpool2/pool_hba.conf regexp="^host {{ item.0.name }} {{ item.0.user }} {{ item.1 }}.*$" line="host {{ item.0.name }} {{ item.0.user }} {{ item.1 }} md5"
  with_subelements: 
    - '{{ psql_db_data | default([]) }}'
    - allowed_hosts
  when:
    - psql_db_data is defined
    - item.1 is defined
  notify: Reload pgpool2
  tags: [ 'postgresql', 'postgres', 'pgpool', 'pgpool_conf' ]
  
- name: Install the pool_passwd configuration file
  shell: cd /etc/pgpool2 ; pg_md5 -m -u {{ item.user }} {{ item.pwd }} ; chown root:postgres /etc/pgpool2/pool_passwd ; chmod 660 /etc/pgpool2/pool_passwd
  with_items: '{{ psql_db_data | default([]) }}'
  tags: [ 'postgresql', 'postgres', 'pgpool', 'pgpool_conf' ]
  
- name: Start and enable pgpool2
  service: name=pgpool2 state=started enabled=yes
  when: pgpool_enabled
  tags: [ 'postgresql', 'postgres', 'pgpool' ]

- name: Stop and disable pgpool2
  service: name=pgpool2 state=stopped enabled=no
  when: not pgpool_enabled
  tags: [ 'postgresql', 'postgres', 'pgpool' ]