#!/usr/bin/python
# -*- mode: python; coding: utf-8 -*-
# 
# Mandos Monitor - Control and monitor the Mandos server
# 
# Copyright © 2008-2012 Teddy Hogeborn
# Copyright © 2008-2012 Björn Påhlsson
# 
# 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/>.
# 
# Contact the authors at <mandos@recompile.se>.
# 

from __future__ import (division, absolute_import, print_function,
                        unicode_literals)

from future_builtins import *

import sys
import dbus
import argparse
import locale
import datetime
import re
import os

locale.setlocale(locale.LC_ALL, "")

tablewords = {
    "Name": "Name",
    "Enabled": "Enabled",
    "Timeout": "Timeout",
    "LastCheckedOK": "Last Successful Check",
    "LastApprovalRequest": "Last Approval Request",
    "Created": "Created",
    "Interval": "Interval",
    "Host": "Host",
    "Fingerprint": "Fingerprint",
    "CheckerRunning": "Check Is Running",
    "LastEnabled": "Last Enabled",
    "ApprovalPending": "Approval Is Pending",
    "ApprovedByDefault": "Approved By Default",
    "ApprovalDelay": "Approval Delay",
    "ApprovalDuration": "Approval Duration",
    "Checker": "Checker",
    "ExtendedTimeout" : "Extended Timeout"
    }
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
domain = "se.recompile"
busname = domain + ".Mandos"
server_path = "/"
server_interface = domain + ".Mandos"
client_interface = domain + ".Mandos.Client"
version = "1.6.0"

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 ("{days}{hours:02}:{minutes:02}:{seconds:02}"
            .format(days = "{0}T".format(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("1w")
    datetime.timedelta(7)
    >>> string_to_delta("5m 30s")
    datetime.timedelta(0, 330)
    """
    value = datetime.timedelta(0)
    regexp = re.compile("(\d+)([dsmhw]?)")
    
    for num, suffix in regexp.findall(interval):
        if suffix == "d":
            value += datetime.timedelta(int(num))
        elif suffix == "s":
            value += datetime.timedelta(0, int(num))
        elif suffix == "m":
            value += datetime.timedelta(0, 0, 0, 0, int(num))
        elif suffix == "h":
            value += datetime.timedelta(0, 0, 0, 0, 0, int(num))
        elif suffix == "w":
            value += datetime.timedelta(0, 0, 0, 0, 0, 0, int(num))
        elif suffix == "":
            value += datetime.timedelta(0, 0, 0, int(num))
    return value

def print_clients(clients, keywords):
    def valuetostring(value, keyword):
        if type(value) is dbus.Boolean:
            return "Yes" if value else "No"
        if keyword in ("Timeout", "Interval", "ApprovalDelay",
                       "ApprovalDuration", "ExtendedTimeout"):
            return milliseconds_to_string(value)
        return unicode(value)
    
    # Create format string to print table rows
    format_string = " ".join("{{{key}:{width}}}".format(
            width = max(len(tablewords[key]),
                        max(len(valuetostring(client[key],
                                              key))
                            for client in
                            clients)),
            key = key) for key in keywords)
    # Print header line
    print(format_string.format(**tablewords))
    for client in clients:
        print(format_string.format(**dict((key,
                                           valuetostring(client[key],
                                                         key))
                                          for key in keywords)))

def has_actions(options):
    return any((options.enable,
                options.disable,
                options.bump_timeout,
                options.start_checker,
                options.stop_checker,
                options.is_enabled,
                options.remove,
                options.checker is not None,
                options.timeout is not None,
                options.extended_timeout is not None,
                options.interval is not None,
                options.approved_by_default is not None,
                options.approval_delay is not None,
                options.approval_duration is not None,
                options.host is not None,
                options.secret is not None,
                options.approve,
                options.deny))

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--version", action="version",
                        version = "%(prog)s {0}".format(version),
                        help="show version number and exit")
    parser.add_argument("-a", "--all", action="store_true",
                        help="Select all clients")
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="Print all fields")
    parser.add_argument("-e", "--enable", action="store_true",
                        help="Enable client")
    parser.add_argument("-d", "--disable", action="store_true",
                        help="disable client")
    parser.add_argument("-b", "--bump-timeout", action="store_true",
                        help="Bump timeout for client")
    parser.add_argument("--start-checker", action="store_true",
                        help="Start checker for client")
    parser.add_argument("--stop-checker", action="store_true",
                        help="Stop checker for client")
    parser.add_argument("-V", "--is-enabled", action="store_true",
                        help="Check if client is enabled")
    parser.add_argument("-r", "--remove", action="store_true",
                        help="Remove client")
    parser.add_argument("-c", "--checker",
                        help="Set checker command for client")
    parser.add_argument("-t", "--timeout",
                        help="Set timeout for client")
    parser.add_argument("--extended-timeout",
                        help="Set extended timeout for client")
    parser.add_argument("-i", "--interval",
                        help="Set checker interval for client")
    parser.add_argument("--approve-by-default", action="store_true",
                        default=None, dest="approved_by_default",
                        help="Set client to be approved by default")
    parser.add_argument("--deny-by-default", action="store_false",
                        dest="approved_by_default",
                        help="Set client to be denied by default")
    parser.add_argument("--approval-delay",
                        help="Set delay before client approve/deny")
    parser.add_argument("--approval-duration",
                        help="Set duration of one client approval")
    parser.add_argument("-H", "--host", help="Set host for client")
    parser.add_argument("-s", "--secret", type=file,
                        help="Set password blob (file) for client")
    parser.add_argument("-A", "--approve", action="store_true",
                        help="Approve any current client request")
    parser.add_argument("-D", "--deny", action="store_true",
                        help="Deny any current client request")
    parser.add_argument("client", nargs="*", help="Client name")
    options = parser.parse_args()
    
    if has_actions(options) and not (options.client or options.all):
        parser.error("Options require clients names or --all.")
    if options.verbose and has_actions(options):
        parser.error("--verbose can only be used alone or with"
                     " --all.")
    if options.all and not has_actions(options):
        parser.error("--all requires an action.")
    
    try:
        bus = dbus.SystemBus()
        mandos_dbus_objc = bus.get_object(busname, server_path)
    except dbus.exceptions.DBusException:
        print("Could not connect to Mandos server",
              file=sys.stderr)
        sys.exit(1)
    
    mandos_serv = dbus.Interface(mandos_dbus_objc,
                                 dbus_interface = server_interface)
    
    #block stderr since dbus library prints to stderr
    null = os.open(os.path.devnull, os.O_RDWR)
    stderrcopy = os.dup(sys.stderr.fileno())
    os.dup2(null, sys.stderr.fileno())
    os.close(null)
    try:
        try:
            mandos_clients = mandos_serv.GetAllClientsWithProperties()
        finally:
            #restore stderr
            os.dup2(stderrcopy, sys.stderr.fileno())
            os.close(stderrcopy)
    except dbus.exceptions.DBusException:
        print("Access denied: Accessing mandos server through dbus.",
              file=sys.stderr)
        sys.exit(1)
    
    # Compile dict of (clients: properties) to process
    clients={}
    
    if options.all or not options.client:
        clients = dict((bus.get_object(busname, path), properties)
                       for path, properties in
                       mandos_clients.iteritems())
    else:
        for name in options.client:
            for path, client in mandos_clients.iteritems():
                if client["Name"] == name:
                    client_objc = bus.get_object(busname, path)
                    clients[client_objc] = client
                    break
            else:
                print("Client not found on server: {0!r}"
                      .format(name), file=sys.stderr)
                sys.exit(1)
    
    if not has_actions(options) and clients:
        if options.verbose:
            keywords = ("Name", "Enabled", "Timeout",
                        "LastCheckedOK", "Created", "Interval",
                        "Host", "Fingerprint", "CheckerRunning",
                        "LastEnabled", "ApprovalPending",
                        "ApprovedByDefault",
                        "LastApprovalRequest", "ApprovalDelay",
                        "ApprovalDuration", "Checker",
                        "ExtendedTimeout")
        else:
            keywords = defaultkeywords
        
        print_clients(clients.values(), keywords)
    else:
        # Process each client in the list by all selected options
        for client in clients:
            def set_client_prop(prop, value):
                """Set a Client D-Bus property"""
                client.Set(client_interface, prop, value,
                           dbus_interface=dbus.PROPERTIES_IFACE)
            def set_client_prop_ms(prop, value):
                """Set a Client D-Bus property, converted
                from a string to milliseconds."""
                set_client_prop(prop,
                                timedelta_to_milliseconds
                                (string_to_delta(value)))
            if options.remove:
                mandos_serv.RemoveClient(client.__dbus_object_path__)
            if options.enable:
                set_client_prop("Enabled", dbus.Boolean(True))
            if options.disable:
                set_client_prop("Enabled", dbus.Boolean(False))
            if options.bump_timeout:
                set_client_prop("LastCheckedOK", "")
            if options.start_checker:
                set_client_prop("CheckerRunning", dbus.Boolean(True))
            if options.stop_checker:
                set_client_prop("CheckerRunning", dbus.Boolean(False))
            if options.is_enabled:
                sys.exit(0 if client.Get(client_interface,
                                         "Enabled",
                                         dbus_interface=
                                         dbus.PROPERTIES_IFACE)
                         else 1)
            if options.checker is not None:
                set_client_prop("Checker", options.checker)
            if options.host is not None:
                set_client_prop("Host", options.host)
            if options.interval is not None:
                set_client_prop_ms("Interval", options.interval)
            if options.approval_delay is not None:
                set_client_prop_ms("ApprovalDelay",
                                   options.approval_delay)
            if options.approval_duration is not None:
                set_client_prop_ms("ApprovalDuration",
                                   options.approval_duration)
            if options.timeout is not None:
                set_client_prop_ms("Timeout", options.timeout)
            if options.extended_timeout is not None:
                set_client_prop_ms("ExtendedTimeout",
                                   options.extended_timeout)
            if options.secret is not None:
                set_client_prop("Secret",
                                dbus.ByteArray(options.secret.read()))
            if options.approved_by_default is not None:
                set_client_prop("ApprovedByDefault",
                                dbus.Boolean(options
                                             .approved_by_default))
            if options.approve:
                client.Approve(dbus.Boolean(True),
                               dbus_interface=client_interface)
            elif options.deny:
                client.Approve(dbus.Boolean(False),
                               dbus_interface=client_interface)

if __name__ == "__main__":
    main()
