import os

import testinfra.utils.ansible_runner
import time

testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ["MOLECULE_INVENTORY_FILE"]).get_hosts("db0-default")


def test_postgresql_delete_data(host):
    ''' delete data directory '''

    s = host.ansible("command", "rm -rf /var/lib/postgresql/11/main/", become=True, check=False)
    assert s['changed']


def test_postgresql_launch_repmgr_sync(host):
    ''' sync data with primary server using repmgr '''

    current_master = testinfra.utils.ansible_runner.AnsibleRunner(os.environ["MOLECULE_INVENTORY_FILE"]).get_host("db1-default")
    current_master_ip = current_master.interface('eth0').addresses[0]
    rep_mgr_command = "repmgr -f /etc/postgresql/11/main/repmgr.conf --force --verbose standby clone -h " + current_master_ip + " -d repmgr -U repmgr -c"
    s = host.ansible("command", rep_mgr_command, become=True, become_user='postgres', check=False)
    assert s['changed']


def test_postgresql_start_postgresql(host):
    ''' start postgresql '''

    s = host.ansible("command", "systemctl start postgresql", become=True, check=False)
    time.sleep(20)
    assert s['changed']


def test_pogresql_register_as_standby(host):
    ''' register server as standby in repmgr '''

    s = host.ansible("command", "repmgr -f /etc/postgresql/11/main/repmgr.conf --force --verbose standby register", become=True, become_user='postgres', check=False)
    time.sleep(20)
    assert s['changed']