#!/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>
# Fixes by Aleksey Nogin <ayn2@cornell.edu>
#
# 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 -hP -x none -x tmpfs -x iso9660 %s" % ignore).readlines()

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

for line in list[1:]:
    (volume, total, used, avail, pct, mountpt) = string.split(line)
    
    nPct = long(pct[:-1])
    mountpt = string.strip(mountpt)

    if re.search("%s" % volume, exclude): continue
    if cutoff.has_key(volume):
        if (nPct < cutoff[volume]): continue
    elif cutoff.has_key(mountpt):
        if (nPct < cutoff[mountpt]): continue
    elif (nPct < defaultCutoff): continue

    high = 1
    message.append("%s (%s) is %s full -- %s of %s used, %s remain\n" %
                   (volume, mountpt, pct, used, total, avail))

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)
