#!/usr/bin/env python
########################################################################
### FILE:	greylist
### PURPOSE:	Command line interface to "greylistd(8)"
########################################################################

from socket       import socket, AF_UNIX, SOCK_STREAM
from sys          import argv, stdout, stderr, exit
from ConfigParser import ConfigParser

conffile = "/etc/greylistd/config"
sockfile = "/var/run/greylistd/socket"

### Commands that can be given over the socket
commands = ("add", "delete", "check", "update", "stats", "clear")


def usage (message=None):
    if message:
        out = stderr
        out.write("greylist: %s\n\n"%message)
    else:
        out = stdout
        out.write("Command line interface to \"greylistd(8)\"\n\n")

    out.write(
        "Usage: greylist --help\n"
        "       greylist <action>\n\n"
        "Actions:\n"
        "  add [white|black|grey] <data> ...\n"
        "    Add <data> to the specified list (\"white\" if unspecified).\n\n"
        "  delete <data> ...\n"
        "    Remove <data> from any list.\n\n"
        "  check <data> ...\n"
        "    Check the current status of <data>.\n\n"
        "  update <data> ...\n"
        "    Check the current status of <data>; update lists accordingly.\n"
        "    This is how MTAs would normally use the command.\n\n"
        "  stats [<data> ... ]\n"
        "    Without <data>, give some general hit statistics.\n"
        "    Otherwise, list statistics pertaining to <data>.\n\n"
        "  clear\n"
        "    Remove ALL data and statistics, i.e. reset greylistd(8).\n"
        "    This means that ALL new requests will initially receive\n"
        "    a \"grey\" response.  Use with caution!\n\n")
    exit((0, -1)[not message])


if len(argv) < 2:
    usage("Missing action")

elif argv[1] in ("-h", "--help", "help"):
    usage()

elif not argv[1].lower() in commands:
    usage("Invalid command: '%s'"%argv[1])



confParser = ConfigParser()
confParser.read(conffile)
try:
    sockfile = confParser.get("socket", "path")
except:
    pass
del confParser


sock = socket(AF_UNIX, SOCK_STREAM)

try:
    sock.connect(sockfile)
except Exception, e:
    stderr.write("%s: %s\n"%(sockfile, e[1]))
    exit(-1)

try:
    sock.send(" ".join(argv[1:]))
except Exception, e:
    stderr.write("%s: %s\n"%(sockfile, e[1]))
    exit(-1)


stat = sock.recv(1024).strip()
stdout.write("%s\n"%stat)

if (stat.startswith("error:")):
    exit(-1)

elif (stat == "black"):
    exit(2)
    
elif (stat == "grey"):
    exit(1)

else:
    exit(0)

