#!/usr/bin/env python

##############################################################################
# Copyright (C) 2003 Cory Wright - http://www.standblue.net/                 #
#                                                                            #
# This program 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; either version 2 of the License, or          #
# (at your option) any later version.                                        #
#                                                                            #
# This program 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.                               #
#                                                                            #
# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  #
#                                                                            #
##############################################################################

"""
spamchart-report.py v%(Version)s

    -s
    --stdout
       Print the message to standard output after reporting.  Note that
       in spamchart-report.py the default is to *not* print anything.

    -d
    --debug
       Print debugging information about what would have been done, but
       do not really perform any updates.

    -u
    --url
       What URL to use when submitting information.  The URL must take
       three parameters:

          score        -- the value of 'hits=' in X-Spam-Status
          threshold    -- the value of 'required=' in X-Spam-Status
          size         -- the size of the message

       The default URL is http://zebulon.miester.org/spam/report.php

Written by Cory Wright
http://projects.standblue.net/software/index.moto#spamsearch.py
"""

import getopt
import email
import sys
from urllib import urlopen
from cStringIO import StringIO

Version = 0.1
Revision = "$Id: spamchart-report.py,v 1.2 2003/06/19 22:13:10 cwright Exp $"
# default configuration
config = { "stdout" : 0,
           "debug" : 0,
           "url" : "http://zebulon.miester.org/spam/report.php" }

def usage(ret):
    print __doc__ % globals()
    sys.exit(ret)

def main():
    
    try:
        opts, args = getopt.getopt(sys.argv[1:],
                                   'dhsu:', ['debug',
                                             'help',
                                             'stdout',
                                             'url='])
    except getopt.error, msg:
        usage(1)

    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage(0)
        elif opt in ('-d','--debug'):
            config["debug"] = 1
        elif opt in ('-s','--stdout'):
            config["stdout"] = 1
        elif opt in ('-u','--url'):
            config["url"] = arg
        else:
            usage(1)

    original = StringIO(sys.stdin.read())
    try:
        message = email.message_from_file(original)
    except:
        # broken message format, there is nothing we can do, so
        # just bail out
        sys.exit(0)

    original.seek(0)

    try:
        x_spam_status = message["X-Spam-Status"].split("\n")[0]
        score = x_spam_status.split(" ")[1].split("=")[1]
        required = x_spam_status.split(" ")[2].split("=")[1]
        msgsize = len(original.read())
        original.seek(0)

        if float(score) >= float(required):
            geturl = "%s?score=%s&threshold=%s&size=%s" % (config["url"],score,required,msgsize)

            if config["debug"] == 1:
                print "DEBUG: %s" % geturl
            else:
                try:
                    urlopen(geturl).read()
                except IOError, e:
                    print "error: unable to open %s: %s" % (geturl,e)

        if config["debug"] == 1:
            # if debug then pretty print it, otherwise format for logfiles
            print "DEBUG: Found Score: %s" % score
            print "DEBUG: Found Required: %s" % required
            print "DEBUG: Size: %s" % msgsize
        else:
            print "score=%s threshold=%s size=%s" % (score,required,msgsize)

    except:
        # no spam header
        if config["debug"] == 1:
            print "DEBUG: No X-Spam-Status header field was found"

    if config["stdout"] == 1:
        while 1:
            a = sys.stdin.readline()
            if not a: break
            print a,

if __name__ == '__main__':
    # dirty deeds, done dirt cheap
    main()
