#!/usr/bin/env python
# -*- coding: utf-8 -*-
# kate: space-indent on; indent-width 4; replace-tabs on;

"""
 *  Copyright (C) 2011-2016, it-novum GmbH <community@openattic.org>
 *
 *  openATTIC 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; version 2.
 *
 *  This package 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.
"""

import dbus
import sys
from optparse import OptionParser

exitstatus = 0
parser = OptionParser()


parser.add_option( "-d", "--dbus",
    help="DBus service to connect to.",
    default="org.openattic.systemd"
    )

parser.add_option( "-w", "--warning", type="float",
    help="snapshot is at 50 %.", default=50
    )
parser.add_option("-c", "--critical", type="float",
    help="snapshot is at 70%", default=70
    )

options, progargs = parser.parse_args()

if len(progargs) != 1:
    print("Usage: check_openattic_snapshot <lv name>")
    sys.exit(2)

try:
    stats = dbus.SystemBus().get_object(options.dbus, "/lvm").lvs()
except dbus.exceptions.DBusException:
    print "Could not query Systemd"
    sys.exit(3)


def dbus_type_to_python(obj):
    """ Convert a single dbus something to its python equivalent. """
    conv = {
        dbus.Array: list,
        dbus.Dictionary: dict,
        dbus.Boolean: bool,
        dbus.Int16: int,
        dbus.Int32: int,
        dbus.Int64: int,
        dbus.String: unicode,
        dbus.Struct: tuple,
        tuple: tuple
        }
    return conv[type(obj)](obj)

def dbus_to_python(obj):
    """ Recursively convert a dbus something to its python equivalent,
        recursing over lists and dicts.
    """
    py = dbus_type_to_python(obj)
    if isinstance(py, list):
        return [dbus_to_python(el) for el in py]
    elif isinstance(py, tuple):
        return tuple([dbus_to_python(el) for el in py])
    elif isinstance(py, dict):
        return dict([(dbus_type_to_python(key),
        dbus_to_python(obj[key])) for key in py])
    return py

lvname = progargs[0]

if "LVM2_DATA_PERCENT" in stats[lvname]:
    lv_percent = float(stats[lvname]["LVM2_DATA_PERCENT"])
else:
    lv_percent = float(stats[lvname]["LVM2_SNAP_PERCENT"])

normal = ("snapshot %s is at %.2f%% "%(lvname, lv_percent)+"|"
" util_percent=%.2f%%;%.f;%.f "%(lv_percent, options.warning, options.critical))

if stats[lvname]["LVM2_ORIGIN"] == "":
    print("Sie haben ein Originalvolume ausgewählt!")
    sys.exit(2)


lv_origin = stats[lvname]["LVM2_ORIGIN"]

if float(stats[lvname]["LVM2_LV_SIZE"]) >= float(stats[lv_origin]["LVM2_LV_SIZE"]):
    exitstatus = 0
    print(normal)


elif float(stats[lvname]["LVM2_LV_SIZE"]) <= float(stats[lv_origin]["LVM2_LV_SIZE"]):
    if lv_percent > options.critical:
        exitstatus = 2
        print(normal)

    elif lv_percent > options.warning:
        exitstatus = 1
        print(normal)

    elif lv_percent < options.critical and options.warning:
        exitstatus = 0
        print(normal)


sys.exit(exitstatus)
