---
- name: Install nfs-common
  apt: name=nfs-common state=present update_cache=yes cache_valid_time=900

- name: Set 'hot_standby = on' for slave postgresql instance
  lineinfile:
    state: present
    regex: "^hot_standby "
    line: "hot_standby = on"
    path: /etc/postgresql/{{ default_postgres_version }}/main/postgresql.conf

- name: Set 'hot_standby_feedback = on' for slave postgresql instance
  lineinfile:
    state: present
    regex: "^hot_standby_feedback"
    line: "hot_standby_feedback = on"
    path: /etc/postgresql/{{ default_postgres_version }}/main/postgresql.conf

- name: "Setting hosts configuration for for db-master and db-backups in /etc/hosts"
  blockinfile:
    marker: "# {mark} managed by ansible (hosts config for db-master and db-backups)"
    path: "/etc/hosts"
    mode: "0644"
    state: present
    create: yes
    block: |
      {{ shared_service_pg_master_ip + ' ' + 'db-master' }}
      {{ shared_service_pg_master_ip + ' ' + 'db-backup' }}

- name: Wait for nfsd is up and running
  wait_for:
    host: "{{ shared_service_pg_master_ip }}"
    port: 2049

- name: Mount replication NFS volume
  ansible.posix.mount:
    src: db-master:/postgresql/replication
    path: /postgresql/replication
    opts: "rw,bg,hard,nfsvers=4.2,x-systemd.automount,x-systemd.requires=network-online.target,x-systemd.device-timeout=60 0 0"
    state: mounted
    fstype: nfs

- name: Stop postgres on slave
  service:
    name: postgresql
    state: stopped

- name: Remove db data from db-slave
  file:
    state: absent
    path: /var/lib/postgresql/{{ default_postgres_version }}/main/

- name: Wait for db-master is up and running
  wait_for:
    host: "{{ shared_service_pg_master_ip }}"
    port: 5432

- name: Sync data from db-master # noqa command-instead-of-shell no-changed-when
  become: yes
  become_user: postgres
  shell: "pg_basebackup -h {{ shared_service_pg_master_ip }} -D /var/lib/postgresql/{{ default_postgres_version }}/main -U replicator -P -v  -R -X stream -S pgstandby1"
  register: pg_basebackup

- name: Change restore_command in postgresql.conf
  lineinfile:
    path: /etc/postgresql/{{ default_postgres_version }}/main/postgresql.conf
    regex: "^restore_command"
    line: "restore_command = 'cp -f /postgresql/replication/%f %p'"

- name: Change archive_cleanup_command in postgresql.conf
  lineinfile:
    path: /etc/postgresql/{{ default_postgres_version }}/main/postgresql.conf
    regex: "^archive_cleanup_command"
    line: "archive_cleanup_command = 'pg_archivecleanup -d /postgresql/replication %r 2>>cleanup.log'"

- name: Change recovery_target_timeline in postgresql.conf
  lineinfile:
    path: /etc/postgresql/{{ default_postgres_version }}/main/postgresql.conf
    regex: "^recovery_target_timeline"
    line: "recovery_target_timeline = 'latest'"

- name: Start postgres
  service:
    name: postgresql
    state: started
