# implement samba_tool drs commands
#
# Copyright Andrew Tridgell 2010
#
# based on C implementation by Kamen Mazdrashki <kamen.mazdrashki@postpath.com>
#
# 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 samba.getopt as options
import ldb

from samba.auth import system_session
from samba.netcmd import (
    Command,
    CommandError,
    Option,
    SuperCommand,
    )
from samba.samdb import SamDB
from samba import drs_utils, nttime2string, dsdb
from samba.dcerpc import drsuapi, misc
import common

def drsuapi_connect(ctx):
    '''make a DRSUAPI connection to the server'''
    try:
        (ctx.drsuapi, ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drsuapi_connect(ctx.server, ctx.lp, ctx.creds)
    except Exception, e:
        raise CommandError("DRS connection to %s failed" % ctx.server, e)

def samdb_connect(ctx):
    '''make a ldap connection to the server'''
    try:
        ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
                          session_info=system_session(),
                          credentials=ctx.creds, lp=ctx.lp)
    except Exception, e:
        raise CommandError("LDAP connection to %s failed" % ctx.server, e)

def drs_errmsg(werr):
    '''return "was successful" or an error string'''
    (ecode, estring) = werr
    if ecode == 0:
        return "was successful"
    return "failed, result %u (%s)" % (ecode, estring)



def attr_default(msg, attrname, default):
    '''get an attribute
 from a ldap msg with a default'''
    if attrname in msg:
        return msg[attrname][0]
    return default



def drs_parse_ntds_dn(ntds_dn):
    '''parse a NTDS DN returning a site and server'''
    a = ntds_dn.split(',')
    if a[0] != "CN=NTDS Settings" or a[2] != "CN=Servers" or a[4] != 'CN=Sites'
:
        raise RuntimeError("bad NTDS DN %s" % ntds_dn)
    server = a[1].split('=')[1]
    site   = a[3].split('=')[1]
    return (site, server)





class cmd_drs_showrepl(Command):
    """Show replication status."""

    synopsis = "%prog [<DC>] [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptions,
    }

    takes_args = ["DC?"]

    def print_neighbour(self, n):
        '''print one set of neighbour information'''
        self.message("%s" % n.naming_context_dn)
        try:
            (site, server) = drs_parse_ntds_dn(n.source_dsa_obj_dn)
            self.message("\t%s\%s via RPC" % (site, server))
        except RuntimeError:
            self.message("\tNTDS DN: %s" % n.source_dsa_obj_dn)
        self.message("\t\tDSA object GUID: %s" % n.source_dsa_obj_guid)
        self.message("\t\tLast attempt @ %s %s" % (nttime2string(n.last_attempt),
                                                   drs_errmsg(n.result_last_attempt)))
        self.message("\t\t%u consecutive failure(s)." % n.consecutive_sync_failures)
        self.message("\t\tLast success @ %s" % nttime2string(n.last_success))
        self.message("")

    def drsuapi_ReplicaInfo(ctx, info_type):
        '''call a DsReplicaInfo'''

        req1 = drsuapi.DsReplicaGetInfoRequest1()
        req1.info_type = info_type
        try:
            (info_type, info) = ctx.drsuapi.DsReplicaGetInfo(ctx.drsuapi_handle, 1, req1)
        except Exception, e:
            raise CommandError("DsReplicaGetInfo of type %u failed" % info_type, e)
        return (info_type, info)

    def run(self, DC=None, sambaopts=None,
            credopts=None, versionopts=None, server=None):

        self.lp = sambaopts.get_loadparm()
        if DC is None:
            DC = common.netcmd_dnsname(self.lp)
        self.server = DC
        self.creds = credopts.get_credentials(self.lp, fallback_machine=True)

        drsuapi_connect(self)
        samdb_connect(self)

        # show domain information
        ntds_dn = self.samdb.get_dsServiceName()
        server_dns = self.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])[0]['dnsHostName'][0]

        (site, server) = drs_parse_ntds_dn(ntds_dn)
        try:
            ntds = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=['options', 'objectGUID', 'invocationId'])
        except Exception, e:
            raise CommandError("Failed to search NTDS DN %s" % ntds_dn)
        conn = self.samdb.search(base=ntds_dn, expression="(objectClass=nTDSConnection)")

        self.message("%s\\%s" % (site, server))
        self.message("DSA Options: 0x%08x" % int(attr_default(ntds[0], "options", 0)))
        self.message("DSA object GUID: %s" % self.samdb.schema_format_value("objectGUID", ntds[0]["objectGUID"][0]))
        self.message("DSA invocationId: %s\n" % self.samdb.schema_format_value("objectGUID", ntds[0]["invocationId"][0]))

        self.message("==== INBOUND NEIGHBORS ====\n")
        (info_type, info) = self.drsuapi_ReplicaInfo(drsuapi.DRSUAPI_DS_REPLICA_INFO_NEIGHBORS)
        for n in info.array:
            self.print_neighbour(n)


        self.message("==== OUTBOUND NEIGHBORS ====\n")
        (info_type, info) = self.drsuapi_ReplicaInfo(drsuapi.DRSUAPI_DS_REPLICA_INFO_REPSTO)
        for n in info.array:
            self.print_neighbour(n)

        reasons = ['NTDSCONN_KCC_GC_TOPOLOGY',
                   'NTDSCONN_KCC_RING_TOPOLOGY',
                   'NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY',
                   'NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY',
                   'NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY',
                   'NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY',
                   'NTDSCONN_KCC_INTERSITE_TOPOLOGY',
                   'NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY',
                   'NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY',
                   'NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY']

        self.message("==== KCC CONNECTION OBJECTS ====\n")
        for c in conn:
            self.message("Connection --")

            c_rdn, sep, c_server_dn = c['fromServer'][0].partition(',')
            try:
                c_server_res = self.samdb.search(base=c_server_dn, scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
                c_server_dns = c_server_res[0]["dnsHostName"][0]
            except ldb.LdbError, (errno, _):
                if errno == ldb.ERR_NO_SUCH_OBJECT:
                    self.message("\tWARNING: Connection to DELETED server!")
                c_server_dns = ""
            except KeyError:
                c_server_dns = ""

            self.message("\tConnection name: %s" % c['name'][0])
            self.message("\tEnabled        : %s" % attr_default(c, 'enabledConnection', 'TRUE'))
            self.message("\tServer DNS name : %s" % c_server_dns)
            self.message("\tServer DN name  : %s" % c['fromServer'][0])
            self.message("\t\tTransportType: RPC")
            self.message("\t\toptions: 0x%08X" % int(attr_default(c, 'options', 0)))
            if not 'mS-DS-ReplicatesNCReason' in c:
                self.message("Warning: No NC replicated for Connection!")
                continue
            for r in c['mS-DS-ReplicatesNCReason']:
                a = str(r).split(':')
                self.message("\t\tReplicatesNC: %s" % a[3])
                self.message("\t\tReason: 0x%08x" % int(a[2]))
                for s in reasons:
                    if getattr(dsdb, s, 0) & int(a[2]):
                        self.message("\t\t\t%s" % s)



class cmd_drs_kcc(Command):
    """Trigger knowledge consistency center run."""

    synopsis = "%prog [<DC>] [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "version