#!/usr/share/ucs-test/runner python
## desc: Test the Samba SYSVOL replication with multi-school domain setup
## bugs: [34225]
## roles: [domaincontroller_slave]
## packages: [univention-samba4]
## tags: [apptest, ucsschool]
## exposure: dangerous

from sys import exit
from os import path
from re import search, match, IGNORECASE
from subprocess import Popen, PIPE
from time import sleep

import univention.testing.utils as utils
from univention.testing.codes import TestCodes
from univention.config_registry import ConfigRegistry
from univention.testing.strings import random_username


class TestSYSVOLReplicationMultiSchool(object):

    def __init__(self):
        """
        Test class constructor
        """
        self.UCR = ConfigRegistry()

        self.admin_username = ''
        self.admin_password = ''

        self.gpo_reference = ''

    def execute_cmd_on_host(self, host, command_line):
        """
        Logs into the given remote 'host' using 'univention-ssh' and test
        admin credentials and executes there the given 'command_line'.
        Returns the stdout produced on the remote 'host'.
        """
        print("\nAccessing the remote host '%s' using the test "
              "administrator credentials" % host)

        # '/dev/stdin' used to avoid creation of a file with a password:
        proc = Popen(('univention-ssh',
                      '-timeout',
                      '120',
                      '/dev/stdin',
                      self.admin_username + '@' + host,
                      command_line),
                     stdin=PIPE,
                     stdout=PIPE,
                     stderr=PIPE)

        stdout, stderr = proc.communicate(input=self.admin_password)
        if stderr:
            # ignore warnings (both lower/upper case)
            # ("Permanently added to the list of known hosts", etc.):
            if bool(match('Warning|Warnung', stderr, IGNORECASE)):
                print "Ignoring the following warning message:", stderr
            else:
                utils.fail("An error occured while connecting to the remote "
                           "host '%s' via ssh or executing the command: '%s'"
                           % (host, stderr))
        if stdout:
            stdout = stdout.strip()
            print("\nThe output of the command '%s' executed on the remote "
                  "host '%s' is: '%s'" % (command_line, host, stdout))
            return stdout

    def check_sysvol_replication(self, host, wait_sync):
        """
        Executes the command on the given 'host' to check the presence of
        a test GPO folder in Samba sysvol.
        If 'wait_sync'=True: waits before the check to make sure that
        a cron job running sysvol sync was executed at least once.
        """
        print "\nChecking SYSVOL replication to host '%s':" % host

        # max time the replication can take is 5 (+1) mins (cron job schedule)
        if wait_sync:
            sync_time = 370
            print("\nWaiting %d seconds to make sure that SYSVOL "
                  "synchronisation script was run at least once on the '%s'"
                  % (sync_time, host))
            sleep(sync_time)

        # specifing the path to sysvol (with '\' before '{' and '}')
        sysvol_path = ("/var/lib/samba/sysvol/%s/Policies/\%s/"
                       % (self.UCR['domainname'],
                          self.gpo_reference[:-1] + '\}'))

        # command should return 'True' if folder exists and 'False' otherwise:
        command_line = ("[ -d %s ] && echo 'True' || echo 'False'"
                        % sysvol_path)

        remote_stdout = self.execute_cmd_on_host(host, command_line)
        if not remote_stdout:
            utils.fail("The command '%s' executed on the remote host '%s' "
                       "produced no output to 'stdout'" % (command_line, host))
        if remote_stdout != 'True':
            if remote_stdout == 'False':
                utils.fail("The command to check the sysvol replication on a "
                           "remote host '%s' reported that '%s' GPO folder "
                           "does not exist. (Replication did not work)."
                           % (host, self.gpo_reference))

            utils.fail("The command to check the sysvol replication on a "
                       "remote host '%s' did not report that '%s' GPO folder "
                       "exists. Command's stdout from the remote host: '%s'"
                       % (host, self.gpo_reference, remote_stdout))

    def run_local_sysvol_replication(self):
        """
        Triggers 'sysvol-sync.sh' locally.
        """
        repl_script = '/usr/share/univention-samba4/scripts/sysvol-sync.sh'

        print "\nExecuting the replication script '%s'" % repl_script
        if not path.exists(repl_script):
            utils.fail("The replication script '%s' file cannot be found."
                       % repl_script)

        proc = Popen(repl_script, stderr=PIPE)
        stdout, stderr = proc.communicate()
        if stderr:
            utils.fail("An error occured while running the replication script "
                       "'%s': '%s'" % (repl_script, stderr))

    def process_ldap_search_results(self, search_results):
        """
        Removes the 'displayName' from 'search_results' and returns the
        list of slave hostnames in the domain except for the local hostname.
        """
        search_results = search_results.replace('displayName: ', '')
        try:
            slave_hostnames = search_results.split()
            slave_hostnames.remove(self.UCR['hostname'])
        except (ValueError, KeyError) as exc:
            utils.fail("An exception while trying to remove the local "
                       "hostname from the list of all slave hostnames: "
                       "%s" % exc)
        return slave_hostnames

    def get_other_dc_hostnames(self):
        """
        Invokes the 'univention-ldapsearch' with 'ldap_master' as LDAP
        server to get the hostnames of all DC-Slave instances in the domain;
        Excludes the local hostname and returns the list with a DC-Master
        hostname + all the rest DC-Slave hostnames in the domain.
        """
        print("\nGenerating the list of all other DCs in the domain "
              "to check the SYSVOL replication:")
        ldap_master = self.UCR.get('ldap/master')
        search_pattern = 'univentionServerRole=slave'

        proc = Popen(("univention-ldapsearch",
                      "-h",
                      ldap_master,
                      "-p",
                      self.UCR.get('ldap/master/port'),
                      "-D",
                      self.UCR.get('tests/domainadmin/account'),
                      "-w",
                      self.admin_password,
                      search_pattern),
                     stdout=PIPE)

        # reduce the LDAP search results to 'displayName' fields:
        grep_proc = Popen(("grep", "displayName"),
                          stdin=proc.stdout,
                          stdout=PIPE,
                          stderr=PIPE)
        proc.stdout.close()
        stdout, stderr = grep_proc.communicate()
        if stderr:
            utils.fail("An error occured while trying to grep through the "
                       "LDAP search results from the DC-Master: '%s'" % stderr)
        if not stdout or stdout == '\n':
            utils.fail("No output from grep process, possibly an error "
                       "occured during the LDAP search on DC-Master or "
                       "while trying to connect to DC-Master via ssh")

        hosts = [ldap_master] + self.process_ldap_search_results(stdout)
        print "The following hosts will be checked:", hosts
        return hosts

    def get_ucr_test_credentials(self):
        """
        Loads the UCR to get credentials for the test.
        """
        print("Obtatining Administrator username and password "
              "for the test from the UCR")
        try:
            self.UCR.load()

            self.admin_username = self.UCR['tests/domainadmin/account']
            # extracting the 'uid' value of the administrator username string:
            self.admin_username = self.admin_username.split(',')[0][len('uid='):]
            self.admin_password = self.UCR['tests/domainadmin/pwd']
        except KeyError as exc:
            print("\nAn exception while trying to read data from the UCR for "
                  "the test: '%s'. Skipping the test." % exc)
            exit(TestCodes.REASON_INSTALL)

    def delete_samba_gpo(self):
        """
        Deletes the Group Policy Object using the 'samba-tool gpo del'.
        """
        print("\nRemoving previously created Group Policy Object (GPO) with "
              "a reference: %s" % self.gpo_reference)

        proc = Popen(("samba-tool",
                      "gpo",
                      "del",
                      self.gpo_reference,
                      "--username=" + self.admin_username,
                      "--password=" + self.admin_password),
                     stdout=PIPE,
                     stderr=PIPE)
        stdout, stderr = proc.communicate()
        if stderr:
            utils.fail("An error occured while removing the GPO using "
                       "'samba-tool': '%s'" % stderr)
        print "\nSamba-tool produced the following output:", stdout

    def create_samba_gpo(self):
        """
        Creates a Group Policy Object for the test by executing
        'samba-tool gpo create'; saves the GPO reference to
        'self.gpo_reference'.
        """
        display_name = 'ucs_test_school_gpo_' + random_username(8)
        print("\nCreating Group Policy Object (GPO) for the test with "
              "a name '%s' using 'samba-tool'" % display_name)

        proc = Popen(("samba-tool",
                      "gpo",
                      "create",
                      display_name,
                      "--username=" + self.admin_username,
                      "--password=" + self.admin_password),
                     stdout=PIPE,
                     stderr=PIPE)
        stdout, stderr = proc.communicate()
        if stderr:
            utils.fail("An error occured while creating a GPO using "
                       "'samba-tool': '%s'" % stderr)
        if not stdout:
            utils.fail("The 'samba-tool' did not produce any output to "
                       "stdout, while a GPO reference was expected")

        stdout = stdout.rstrip()
        print "\nSamba-tool produced the following output:", stdout
        try:
            # extracting the GPO reference from the stdout:
            self.gpo_reference = '{' + search('{(.+?)}', stdout).group(1) + '}'
        except AttributeError as exc:
            utils.fail("Could not find the GPO reference in the stdout "
                       "'%s' of the 'samba-tool', error: '%s'" % (stdout, exc))

    def check_remote_sysvol_replication(self):
        """
        Run replication checks on all other DCs in the domain.
        """
        for index, host in enumerate(self.get_other_dc_hostnames()):
            if index >= 2:
                # don't wait for sync as it already happened
                # (cases after Master -> all Slaves synced):
                self.check_sysvol_replication(host, False)
            else:
                # do check with waiting for syncronisation
                # (cases Slave -> Master -> all other Slaves):
                self.check_sysvol_replication(host, True)

    def main(self):
        """
        Tests the replication of the Samba SYSVOL with multi-school
        domain setup (DC-Master + any number of Slaves).
        """
        try:
            self.get_ucr_test_credentials()
            self.create_samba_gpo()

            self.run_local_sysvol_replication()
            self.check_remote_sysvol_replication()
        finally:
            if self.gpo_reference:
                self.delete_samba_gpo()


if __name__ == '__main__':
    TestSYSVOLReplication = TestSYSVOLReplicationMultiSchool()
    exit(TestSYSVOLReplication.main())
