#!/usr/bin/python3
# Authors: Rob Crittenden <rcritten@redhat.com>
# Authors: Simo Sorce <ssorce@redhat.com>
#
# Copyright (C) 2009  Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

from __future__ import print_function

import sys
import os
from ipaplatform.paths import paths
try:
    from optparse import OptionParser  # pylint: disable=deprecated-module
    from ipapython import ipautil, config
    from ipaserver.install import installutils
    from ipaserver.install.ldapupdate import LDAPUpdate
    from ipalib import api, errors
    from ipapython.ipa_log_manager import standard_logging_setup
    from ipapython.dn import DN
    from ipaplatform import services
except ImportError as e:
    print("""\
There was a problem importing one of the required Python modules. The
error was:

    %s
""" % e, file=sys.stderr)
    sys.exit(1)

nis_config_dn = DN(('cn', 'NIS Server'), ('cn', 'plugins'), ('cn', 'config'))
compat_dn = DN(('cn', 'Schema Compatibility'), ('cn', 'plugins'), ('cn', 'config'))

def parse_options():
    usage = "%prog [options] <enable|disable|status>\n"
    usage += "%prog [options]\n"
    parser = OptionParser(usage=usage, formatter=config.IPAFormatter())

    parser.add_option("-d", "--debug", action="store_true", dest="debug",
                      help="Display debugging information about the update(s)")
    parser.add_option("-y", dest="password",
                      help="File containing the Directory Manager password")

    config.add_standard_options(parser)
    options, args = parser.parse_args()

    return options, args

def get_dirman_password():
    """Prompt the user for the Directory Manager password and verify its
       correctness.
    """
    password = installutils.read_password("Directory Manager", confirm=False, validate=False, retry=False)

    return password

def get_entry(dn):
    """
    Return the entry for the given DN. If the entry is not found return
    None.
    """
    entry = None
    try:
        entry = api.Backend.ldap2.get_entry(dn)
    except errors.NotFound:
        pass
    return entry

def main():
    retval = 0
    files = [paths.NIS_ULDIF]
    servicemsg = ""

    if os.getegid() != 0:
        sys.exit('Must be root to use this tool.')

    installutils.check_server_configuration()

    options, args = parse_options()

    if len(args) != 1:
        sys.exit("You must specify one action: enable | disable | status")
    elif args[0] not in {"enable", "disable", "status"}:
        sys.exit("Unrecognized action [" + args[0] + "]")

    standard_logging_setup(None, debug=options.debug)
    dirman_password = ""
    if options.password:
        try:
            pw = ipautil.template_file(options.password, [])
        except IOError:
            sys.exit("File \"%s\" not found or not readable" % options.password)
        dirman_password = pw.strip()
    else:
        dirman_password = get_dirman_password()
        if dirman_password is None:
            sys.exit("Directory Manager password required")

    if not dirman_password:
        sys.exit("No password supplied")

    api.bootstrap(
        context='cli', confdir=paths.ETC_IPA,
        debug=options.debug, in_server=True)
    api.finalize()
    api.Backend.ldap2.connect(bind_pw=dirman_password)

    if args[0] == "enable":
        compat = get_entry(compat_dn)
        if compat is None or compat.get('nsslapd-pluginenabled', [''])[0].lower() == 'off':
            sys.exit("The compat plugin needs to be enabled: ipa-compat-manage enable")
        entry = None
        try:
            entry = get_entry(nis_config_dn)
        except errors.ExecutionError as lde:
            print("An error occurred while talking to the server.")
            print(lde)
            retval = 1

        # Enable either the portmap or rpcbind service
        portmap = services.knownservices.portmap
        rpcbind = services.knownservices.rpcbind

        if portmap.is_installed():
            portmap.enable()
            servicemsg = portmap.service_name
        elif rpcbind.is_installed():
            rpcbind.enable()
            servicemsg = rpcbind.service_name
        else:
            print("Unable to enable either %s or %s" % (portmap.service_name, rpcbind.service_name))
            retval = 3

        # The cn=config entry for the plugin may already exist but it
        # could be turned off, handle both cases.
        if entry is None:
            print("Enabling plugin")
            ld = LDAPUpdate(dm_password=dirman_password, sub_dict={}, ldapi=True)
            if ld.update(files) != True:
                retval = 1
        elif entry.get('nsslapd-pluginenabled', [''])[0].lower() == 'off':
            print("Enabling plugin")
            # Already configured, just enable the plugin
            entry['nsslapd-pluginenabled'] = ['on']
            api.Backend.ldap2.update_entry(entry)
        else:
            print("Plugin already Enabled")
            retval = 2

    elif args[0] == "disable":
        try:
            entry = api.Backend.ldap2.get_entry(nis_config_dn, ['nsslapd-pluginenabled'])
            entry['nsslapd-pluginenabled'] = ['off']
            api.Backend.ldap2.update_entry(entry)
        except (errors.NotFound, errors.EmptyModlist):
            print("Plugin is already disabled")
            retval = 2
        except errors.LDAPError as lde:
            print("An error occurred while talking to the server.")
            print(lde)
            retval = 1

    elif args[0] == "status":
        nis_entry = get_entry(nis_config_dn)
        enabled = (nis_entry and
                   nis_entry.get(
                       'nsslapd-pluginenabled', '')[0].lower() == "on")
        if enabled:
            print("Plugin is enabled")
            retval = 0
        else:
            print("Plugin is not enabled")
            retval = 4

    else:
        retval = 1

    if retval == 0:
        if args[0] in {"enable", "disable"}:
            print("This setting will not take effect until you restart "
                  "Directory Server.")

        if args[0] == "enable":
            print("The %s service may need to be started." % servicemsg)

    api.Backend.ldap2.disconnect()

    return retval

if __name__ == '__main__':
    installutils.run_script(main, operation_name='ipa-nis-manage')
