#!/usr/bin/python
# Authors: Rob Crittenden <rcritten@redhat.com>
#
# Copyright (C) 2012  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/>.
#

import sys
import os
import pwd
try:
    from optparse import OptionParser
    from ipapython import ipautil, config
    from ipaserver import ipaldap
    from ipaserver.install import installutils, replication
    from ipaserver.plugins.ldap2 import ldap2
    from ipalib import api, errors
except ImportError:
    print >> sys.stderr, """\
There was a problem importing one of the required Python modules. The
error was:

    %s
""" % sys.exc_value
    sys.exit(1)

def parse_options():
    usage = "%prog [options]\n"
    parser = OptionParser(usage=usage, formatter=config.IPAFormatter())

    parser.add_option("-t", "--test", action="store_true", dest="test",
                      help="Run in test mode, no changes are applied")
    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")

    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)

    return password

def main():
    retval = 0

    options, args = parse_options()

    if os.getegid() == 0:
     installutils.standard_logging_setup("/var/log/ipaserver-fixreplica.log", options.debug, filemode='a')

    api.bootstrap(context='cli', debug=options.debug)
    api.finalize()

    conn = None
    dirman_password = ""
    if os.getegid() == 0:
        conn = ipaldap.IPAdmin(api.env.host, ldapi=True, realm=api.env.realm)
        conn.do_external_bind(pwd.getpwuid(os.geteuid()).pw_name)
    else:
        if options.password:
            pw = ipautil.template_file(options.password, [])
            dirman_password = pw.strip()
        else:
            dirman_password = get_dirman_password()
            if dirman_password is None:
                sys.exit("\nDirectory Manager password required")

    repl = replication.ReplicationManager(api.env.realm, api.env.host,
                                          dirman_password, conn=conn)
    entries = repl.find_replication_agreements()
    print "Found %d agreement(s)" % len(entries)
    for replica in entries:
        print "%s: " % replica.description
        if 'memberof' not in replica.nsDS5ReplicatedAttributeList:
            print "    Attribute list needs updating"
            current = replica.toDict()
            replica.setValue('nsDS5ReplicatedAttributeList',
                replica.nsDS5ReplicatedAttributeList + ' memberof')
            if not options.test:
                try:
                    repl.conn.updateEntry(replica.dn, current, replica.toDict())
                    print "    Updated"
                except Exception, e:
                    print "Error caught updating replica: %s" % str(e)
                    retval = 1
            else:
                print "    Test mode, not updating"
                retval = 2
        else:
            print "    Attribute list ok"

    return retval

try:
    if __name__ == "__main__":
        sys.exit(main())
except RuntimeError, e:
    print "%s" % e
    sys.exit(1)
except SystemExit, e:
    sys.exit(e)
except KeyboardInterrupt, e:
    sys.exit(1)
except config.IPAConfigError, e:
    print "IPA replica not configured."
    sys.exit(0)
except errors.LDAPError, e:
    print "An error occurred while performing operations: %s" % e
    sys.exit(1)
