#!/usr/bin/python
# -*- mode: python; coding: utf-8 -*-

from __future__ import division
import sys
import dbus
from optparse import OptionParser
import locale
import datetime
import re

locale.setlocale(locale.LC_ALL, u'')

tablewords = {
    'name': u'Name',
    'enabled': u'Enabled',
    'timeout': u'Timeout',
    'last_checked_ok': u'Last Successful Check',
    'created': u'Created',
    'interval': u'Interval',
    'host': u'Host',
    'fingerprint': u'Fingerprint',
    'checker_running': u'Check Is Running',
    'last_enabled': u'Last Enabled',
    'checker': u'Checker',
    }
defaultkeywords = ('name', 'enabled', 'timeout', 'last_checked_ok',
                   'checker')
domain = 'se.bsnet.fukt'
busname = domain + '.Mandos'
server_path = '/'
server_interface = domain + '.Mandos'
client_interface = domain + '.Mandos.Client'
version = "1.0.14"
bus = dbus.SystemBus()
mandos_dbus_objc = bus.get_object(busname, server_path)
mandos_serv = dbus.Interface(mandos_dbus_objc,
                             dbus_interface = server_interface)
mandos_clients = mandos_serv.GetAllClientsWithProperties()

def timedelta_to_milliseconds(td):
    "Convert a datetime.timedelta object to milliseconds"
    return ((td.days * 24 * 60 * 60 * 1000)
            + (td.seconds * 1000)
            + (td.microseconds // 1000))

def milliseconds_to_string(ms):
    td = datetime.timedelta(0, 0, 0, ms)
    return (u"%(days)s%(hours)02d:%(minutes)02d:%(seconds)02d"
            % { "days": "%dT" % td.days if td.days else "",
                "hours": td.seconds // 3600,
                "minutes": (td.seconds % 3600) // 60,
                "seconds": td.seconds % 60,
                })


def string_to_delta(interval):
    """Parse a string and return a datetime.timedelta

    >>> string_to_delta('7d')
    datetime.timedelta(7)
    >>> string_to_delta('60s')
    datetime.timedelta(0, 60)
    >>> string_to_delta('60m')
    datetime.timedelta(0, 3600)
    >>> string_to_delta('24h')
    datetime.timedelta(1)
    >>> string_to_delta(u'1w')
    datetime.timedelta(7)
    >>> string_to_delta('5m 30s')
    datetime.timedelta(0, 330)
    """
    timevalue = datetime.timedelta(0)
    regexp = re.compile("\d+[dsmhw]")
    
    for s in regexp.findall(interval):
        try:
            suffix = unicode(s[-1])
            value = int(s[:-1])
            if suffix == u"d":
                delta = datetime.timedelta(value)
            elif suffix == u"s":
                delta = datetime.timedelta(0, value)
            elif suffix == u"m":
                delta = datetime.timedelta(0, 0, 0, 0, value)
            elif suffix == u"h":
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
            elif suffix == u"w":
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
            else:
                raise ValueError
        except (ValueError, IndexError):
            raise ValueError
        timevalue += delta
    return timevalue

def print_clients(clients):
    def valuetostring(value, keyword):
        if type(value) is dbus.Boolean:
            return u"Yes" if value else u"No"
        if keyword in (u"timeout", u"interval"):
            return milliseconds_to_string(value)
        return unicode(value)
    
    # Create format string to print table rows
    format_string = u' '.join(u'%%-%ds' %
                              max(len(tablewords[key]),
                                  max(len(valuetostring(client[key], key))
                                      for client in
                                      clients))
                              for key in keywords)
    # Print header line
    print format_string % tuple(tablewords[key] for key in keywords)
    for client in clients:
        print format_string % tuple(valuetostring(client[key], key)
                                    for key in keywords)

parser = OptionParser(version = "%%prog %s" % version)
parser.add_option("-a", "--all", action="store_true",
                  help="Print all fields")
parser.add_option("-e", "--enable", action="store_true",
                  help="Enable client")
parser.add_option("-d", "--disable", action="store_true",
                  help="disable client")
parser.add_option("-b", "--bump-timeout", action="store_true",
                  help="Bump timeout for client")
parser.add_option("--start-checker", action="store_true",
                  help="Start checker for client")
parser.add_option("--stop-checker", action="store_true",
                  help="Stop checker for client")
parser.add_option("-V", "--is-valid", action="store_true",
                  help="Check if client is still valid")
parser.add_option("-r", "--remove", action="store_true",
                  help="Remove client")
parser.add_option("-c", "--checker", type="string",
                  help="Set checker command for client")
parser.add_option("-t", "--timeout", type="string",
                  help="Set timeout for client")
parser.add_option("-i", "--interval", type="string",
                  help="Set checker interval for client")
parser.add_option("-H", "--host", type="string",
                  help="Set host for client")
parser.add_option("-s", "--secret", type="string",
                  help="Set password blob (file) for client")
options, client_names = parser.parse_args()

# Compile list of clients to process
clients=[]
for name in client_names:
    for path, client in mandos_clients.iteritems():
        if client['name'] == name:
            client_objc = bus.get_object(busname, path)
            clients.append(client_objc)
            break
    else:
        print >> sys.stderr, "Client not found on server: %r" % name
        sys.exit(1)

if not clients and mandos_clients.values():
    keywords = defaultkeywords
    if options.all:
        keywords = ('name', 'enabled', 'timeout', 'last_checked_ok',
                    'created', 'interval', 'host', 'fingerprint',
                    'checker_running', 'last_enabled', 'checker')
    print_clients(mandos_clients.values())

# Process each client in the list by all selected options
for client in clients:
    if options.remove:
        mandos_serv.RemoveClient(client.__dbus_object_path__)
    if options.enable:
        client.Enable(dbus_interface=client_interface)
    if options.disable:
        client.Disable(dbus_interface=client_interface)
    if options.bump_timeout:
        client.CheckedOK(dbus_interface=client_interface)
    if options.start_checker:
        client.StartChecker(dbus_interface=client_interface)
    if options.stop_checker:
        client.StopChecker(dbus_interface=client_interface)
    if options.is_valid:
        sys.exit(0 if client.Get(client_interface,
                                 u"enabled",
                                 dbus_interface=dbus.PROPERTIES_IFACE)
                 else 1)
    if options.checker:
        client.Set(client_interface, u"checker", options.checker,
                   dbus_interface=dbus.PROPERTIES_IFACE)
    if options.host:
        client.Set(client_interface, u"host", options.host,
                   dbus_interface=dbus.PROPERTIES_IFACE)
    if options.interval:
        client.Set(client_interface, u"interval",
                   timedelta_to_milliseconds
                   (string_to_delta(options.interval)),
                   dbus_interface=dbus.PROPERTIES_IFACE)
    if options.timeout:
        client.Set(client_interface, u"timeout",
                   timedelta_to_milliseconds(string_to_delta
                                             (options.timeout)),
                   dbus_interface=dbus.PROPERTIES_IFACE)
    if options.secret:
        client.Set(client_interface, u"secret",
                   dbus.ByteArray(open(options.secret, u'rb').read()),
                   dbus_interface=dbus.PROPERTIES_IFACE)
