#!/usr/bin/env python
#
# Provides: check_space
#
# simple space checker

import os
import argparse


def main(args):
    errors = []

    for item in args.p:
        buf = item.split('|')
        if len(buf) != 3:
            raise Exception("Incorrect value for checking {0}".format(item))
        path = buf[0]
        blocks_level = int(buf[1])
        inode_level = int(buf[2])

        path_stat = os.statvfs(path)

        blocks_usage = ((path_stat.f_blocks - path_stat.f_bfree) / float(path_stat.f_blocks)) * 100.0
        if blocks_usage > blocks_level:
            errors.append("Path: {0} Space usage: {1}".format(path, blocks_usage))

        inode_usage = ((path_stat.f_files - path_stat.f_ffree) / float(path_stat.f_files)) * 100.0
        if inode_usage > inode_level:
            errors.append("Path: {0} Inode usage: {1}".format(path, blocks_usage))

    if len(errors) > 0:
        print "PASSIVE-CHECK:check_space;2;problems: {0}".format(" :: ".join(errors))
    else:
        print "PASSIVE-CHECK:check_space;0;ok"

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Space checker for L7 balancer")
    parser.add_argument("-p", nargs="+", type=str, default=["/|75|75", "/logs|75|75"], help="Mount points to check (e.g '/|20|80' checks / mount point has less than 20%% free blocks and 80%% free inodes)")

    main(parser.parse_args())
