#!/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 os
import sys
import django
import time

from optparse import OptionParser
from configobj import ConfigObj

distro_config = ["/etc/default/openattic", "/etc/sysconfig/openattic"]
for config_file in distro_config:
    if os.path.isfile(config_file):
        config = ConfigObj(config_file)
        sys.path.append(config["OADIR"])
        break
else:
    raise IOError("Can't find the needed configuration file 'openattic' containing the OADIR "
                  "setting. Please reinstall the openattic-base package to get the missing "
                  "configuration file.")

os.environ["DJANGO_SETTINGS_MODULE"] = "settings"

if django.VERSION[:2] >= (1, 7):
    django.setup()


def main():
    from ceph.models import CephPool, fsid_context

    parser = OptionParser(usage="%prog <cluster FSID> <pool name>")
    _, args = parser.parse_args()

    if len(args) != 2:
        parser.print_usage()
        sys.exit(3)

    start_time = time.time()
    try:
        with fsid_context(args[0]):
            pool = CephPool.objects.get(name=args[1])
    except Exception:
        print "CRITICAL"
        sys.exit(2)
    exec_time = time.time() - start_time

    used_per_cent = pool.num_bytes / pool.max_avail * 100
    perfdata = "OK: Used {} M ({}%)|num_bytes={} max_avail={} num_objects={} exec_time={}ms".format(
        pool.num_bytes, used_per_cent, pool.num_bytes, pool.max_avail, pool.num_objects,
        round(exec_time * 1000, 2))

    print perfdata
    sys.exit(0)

if __name__ == "__main__":
    main()
