#!/usr/bin/python
#
# DiskCheck program 1.0
# Copyright (c) 2001 Red Hat, Inc. All rights reserved.
#
# This software may be freely redistributed under the terms of the GNU
# public license.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software 
# Foundation, Inc., 675 Mass Ave, Cambmridge, MA 02139, USA.
#
# Author: Preston Brown <pbrown@redhat.com>
# Inspiration for this program comes from a perl script of the same name
# by Kirk Bauer <kirk@kaybee.org> and Benjamin Cabell <q98@beseix.org>

import sys, os, string, re
from socket import gethostname

if not os.access("/etc/diskcheck.conf", os.R_OK):
    print "Cannot access configuration file /etc/diskcheck.conf."
    sys.exit(1)
else:
    defaultCutoff = 90
    cutoff = {}
    exclude = ""
    ignore = ""
    mailTo = "root@localhost"
    mailFrom = "Disk Usage Monitor <root>"
    mailProg = "/usr/sbin/sendmail"
    
    cfgFile = open("/etc/diskcheck.conf", "r")
    lines = cfgFile.readlines()
    for line in lines:
        line = line[:-1]
        line = string.lstrip(line)
        if line == "":
            continue
        if line[0] == "#":
            continue
        exec(line)

hostname = gethostname()
list = os.popen("df %s" % ignore).readlines()
listHuman = os.popen("df -h %s" % ignore).readlines()

import tempfile
tempfile.tempdir = "/var/spool/cron"

message = []

message.append("To: %s\n" % mailTo)
message.append("From: %s\n" % mailFrom)
message.append("Subject: Low disk space warning\n\n")

message.append("Disk usage for %s:\n\n" % hostname)

high = 0

test = 0

count = 0
for line in list[1:]:
    count = count + 1
    (volume, total, used, avail, pct, mountpt) = string.split(line)
    (null, hTotal, hUsed, hAvail, null, null) = string.split(listHuman[count])
    
    pct = pct[:-1]
    mountpt = string.strip(mountpt)
    if not re.search("%s" % volume, exclude):
        if test or cutoff.has_key(volume):
            if test or pct >= cutoff[volume]:
                high = 1
                message.append("%s (%s) is %s%% full -- %s of %s used, %s remain\n" %
                            (volume, mountpt, pct, hUsed, hTotal, hAvail))
        elif test or cutoff.has_key(mountpt):
            if test or pct >= cutoff[mountpt]:
                high = 1
                message.append("%s (%s) is %s%% full -- %s of %s used, %s remain\n" %
                            (volume, mountpt, pct, hUsed, hTotal, hAvail))

if (high != 0):
    # mail out the message
    mailer = os.popen("%s -t" % mailProg, "w")
    for line in message:
        mailer.write(line)

    mailer.close()

sys.exit(0)
        
    




    
