#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
#  OX for UCS
#  fix passwords of OX context admins that got out of sync
#
# Copyright (C) 2004-2021 Univention GmbH <http://www.univention.de/>
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

import argparse
import os
import re
import shutil
import subprocess
import sys
import time

from univention.lib.i18n import Translation
from univention.ox.listener_tools import get_master_credentials, ox_list_context, ListenerTools_RuntimeError
from univention.ox.oxlogger import OXLogger

from typing import List, Optional, Tuple

CSV_CONTEXT_COL_ID = "id"

def call_cmd(cmd, verbose=False):  # type: (List[str], bool) -> Tuple[str, str, int]
    proc = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        stdin=open("/dev/null", "r"))
    stdout, stderr = [x.decode('utf-8', 'replace') for x in proc.communicate()]
    if verbose:
        print('Command {!r} returned with exitcode {}:\n{}\n{}\n'.format(cmd, proc.returncode, stdout, stderr))
    return stdout, stderr, proc.returncode


def restart_ox(verbose=False):  # type: (bool) -> None
    call_cmd(['service', 'open-xchange', 'restart'], verbose)
    call_cmd(['/usr/sbin/wait_for_ox_server'], verbose)


class ActivateOXMasterAccountOverride(object):
    """
    Context manager that activates the MASTER ACCOUNT OVERRIDE
    in open-xchange. The context manager restarts OX twice:
    once during __enter__ and once during __exit__.

    Please note: the wrapper becomes only active, if
    active=True is given!
    """
    def __init__(self, active, only_errors, verbose):  # type: (bool, bool, bool) -> None
        self.active = active
        self.only_errors = only_errors
        self.verbose = verbose
        self.orig_file = '/opt/open-xchange/etc/AdminDaemon.properties'
        self.backup_file = '{}.fix_context_admin_passwords.{}'.format(self.orig_file, time.time())

    def __enter__(self):  # type: () -> ActivateOXMasterAccountOverride
        if self.active:
            if not self.only_errors:
                print('Fixing broken context admin passwords. This might take some time due to restarts of OX...')

            # create backup of the config file
            shutil.copy2(self.orig_file, self.backup_file)

            # activate MASTER_ACCOUNT_OVERRIDE and restart OX
            with open(self.orig_file, 'r') as fd:
                content = fd.read()
            new_content = re.sub(
                'MASTER_ACCOUNT_OVERRIDE=[^\n\r]*',
                'MASTER_ACCOUNT_OVERRIDE=true',
                content)
            with open(self.orig_file, 'w') as fd:
                fd.write(new_content)

            restart_ox(self.verbose)
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if self.active:
            # restore original config and restart OX
            shutil.copy2(self.backup_file, self.orig_file)
            restart_ox(self.verbose)


def check_context_admin_password(context_admin, context_admin_password, context_id, verbose=False):  # type: (str, str, str, bool) -> str
    """
    Returns "AUTH_OK" if authentication/search has been successful.
    Returns "AUTH_FAIL" if the authentication has failed.
    Returns "ERROR" if something else happened and exitcode != 0.
    """
    cmd = [
        "/opt/open-xchange/sbin/listuser",
        "--adminuser", context_admin,
        "--adminpass={}".format(context_admin_password),
        "-c", context_id,
        "--searchpattern", context_admin,
        "--csv",
    ]
    stdout, stderr, returncode = call_cmd(cmd, verbose)
    if returncode == 0:
        return "AUTH_OK"
    if 'Authentication failed' in (stdout + stderr):
        return "AUTH_FAIL"
    return "ERROR"


def check_and_fix(do_fix=False, only_errors=False, verbose=False, language=None): # type: (bool, bool, bool, Optional[str]) -> int
    trans = Translation("univention-ox-diagnostic")
    trans.set_language(language=language)
    _ = trans.translate

    results = []  # type: List[Tuple[bool, str]]

    ox_master_admin, ox_master_pass = get_master_credentials()

    # get all existing OX contexts
    oxlog = OXLogger('fix-context-admin-passwords')
    oxlog.stdout = False
    for row in ox_list_context(ox_master_admin, ox_master_pass, logger=oxlog):
        context_id = row[CSV_CONTEXT_COL_ID]
        # use correct username for context admin
        context_admin = "oxadmin" if context_id == "10" else "oxadmin-context{}".format(context_id)

        fn_context_secret = "/etc/ox-secrets/context{}.secret".format(context_id)
        if not os.path.isfile(fn_context_secret):
            # if the context secret is missing, then return an error message
            results.append((True, _('Cannot find secret file "{0}" for context {1}!').format(fn_context_secret, context_id)))
        else:
            # otherwise fetch the password
            with open(fn_context_secret, "r") as fp:
                context_admin_password = fp.read().rstrip("\n\r")
            # and check, if the password is working
            authtest = check_context_admin_password(context_admin, context_admin_password, context_id, verbose)
            if authtest == "AUTH_OK" and not only_errors:
                results.append((False, _('The secrets file for context {} is correct.'.format(context_id))))
            else:
                # an error occurred...
                if authtest == "ERROR":
                    # ... but no auth error
                    results.append((True, _('Unknown error when checking context {}!'.format(context_id))))
                else:
                    # ... and it's an auth error
                    if not do_fix:
                        results.append((
                            True,
                            _('Authentication error for context {}! The password in {} is incorrect!'.format(
                                context_id,
                                fn_context_secret
                            ))))
                    else:
                        # try to set the password of the OX context admin to the password read from the password file
                        fix_cmd = [
                            '/opt/open-xchange/sbin/changeuser',
                            '--adminuser', ox_master_admin,
                            '--adminpass={}'.format(ox_master_pass),
                            '--contextid', context_id,
                            '--username', context_admin,
                            '--password={}'.format(context_admin_password),
                        ]
                        call_cmd(fix_cmd, verbose)

                        authtest = check_context_admin_password(context_admin, context_admin_password, context_id, verbose)
                        if authtest == "AUTH_OK" and not only_errors:
                            results.append((False, _('The secrets file for context {} has been fixed successfully.'.format(context_id))))
                        elif authtest != "AUTH_OK":
                            results.append((True, _('Unknown error when fixing password of context {}!'.format(context_id))))

    for result in results:
        print(result[1])
    exitcode = 1 if any([x[0] for x in results]) else 0
    return exitcode


def admin_master_credentials_found():  # type: () -> bool
    try:
        get_master_credentials()
    except ListenerTools_RuntimeError:
        print('ERROR: Unable to read OX admin master credentials!')
        print('ERROR: Cannot check/fix OX context passwords.')
        return False
    return True


def main():  # type: () -> None
    parser = argparse.ArgumentParser(
        description="Script for checking and fixing OX context admin passwords. Please note, that when fixing context admin passwords, OX will be restarted twice!"
    )
    parser.add_argument(
        "--fix",
        dest="do_fix",
        action="store_true",
        default=False,
        help="Specify this option, to fix broken context passwords, otherwise only a check is performed.",
    )
    parser.add_argument(
        "--only-errors",
        dest="only_errors",
        action="store_true",
        default=False,
        help="If specified, only errors are shown",
    )
    parser.add_argument(
        "--language",
        dest="language",
        action="store",
        default=None,
        help="Specify locale for message translation.",
    )
    parser.add_argument(
        "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="If specified, additional messages are shown.",
    )
    args = parser.parse_args()
    if not admin_master_credentials_found():
        sys.exit(2)
    with ActivateOXMasterAccountOverride(args.do_fix, args.only_errors, args.verbose):
        sys.exit(check_and_fix(args.do_fix, args.only_errors, args.verbose, args.language))


if __name__ == "__main__":
    main()
