#!/usr/bin/env python2
"""
    Classes for handling the python menus

    Copyright  The Computer Guys (PTY) Ltd 2002
    Original file by: Ed Pascoe <ed@pascoe.co.za>
    $Id: sendmail,v 1.1 2003/07/07 09:27:17 elp Exp $
"""
__author__  = "Ed Pascoe <ed@pascoe.co.za>"
__date__    = "$Date: 2003/07/07 09:27:17 $ "
__version__ = "$Revision: 1.1 $"
__credits__ = "Afrihost.com -- The best webhosting. Ever."

import os.path, sys

import os.path, sys
import os
import HTMLParser,urllib
import smtplib
import re

#{{{ class ApachePS(HTMLParser.HTMLParser):
class ApachePS(HTMLParser.HTMLParser):
    trcount=0
    tdcount=0
    data=[]
    currentline=[]
    def __init__(self):
        HTMLParser.HTMLParser.__init__(self)
    def reset(self):
        HTMLParser.HTMLParser.reset(self)
        self.trcount=0
        self.tdcount=0
        data=[]

    def handle_starttag(self,tag,attrs):
        if tag=="tr": 
            self.trcount=self.trcount+1
            if self.trcount==1: self.currentline=[]
        elif tag=="td": self.tdcount=self.tdcount+1

    def handle_endtag(self,tag):
        if tag=="tr": 
            self.trcount=self.trcount-1
            if self.trcount==0:
                self.data.append(self.currentline)
                return
        if tag=="td": 
            self.tdcount=self.tdcount-1

    def handle_data(self,data):
        if self.trcount==1 and self.tdcount==1: self.currentline.append(data)

    def getps(self):
        try:
            return self._getps()
        except Exception,e:
            return "Lookup failed due to "+str(e[0])

    def _getps(self):
        self.reset()
        doc=urllib.urlopen("http://127.0.0.1/whm-server-status").read()
        #print doc
        a=ApachePS()
        a.feed(doc)
        a.close()
        parentid=str(os.getppid())
        for l in  a.data:
            try:
                if l[1]==parentid:
                    return " ".join(l[11:14])
            except IndexError: pass
        return "Unknown process"
#}}}    
#{{{ class Sendmailti:
class Sendmailti:
    """Used to duplicate the effect of piping a message to sendmail -t -i
    """
    mailhost="127.0.0.1"
    mailfrom='<nobody@blofeld.co.za>'
    mailto=[]
    msgheader=[] 
    msgbody=[]
    #{{{ def read(self):
    def read(self):
        """Read in the email message from stdin and obtain a list of addresses to send to"""
        self._newmsg()
        for line in sys.stdin.readlines(): self._linein(line)
    #}}}
    #{{{def inject(self,msg):
    def inject(self,msg):
        """Deals with a supplied msg otherwise same as read()"""
        self._newmsg()
        for line in msg.split("\n"): self._linein(line+"\n")
    #}}}
    #{{{ def _newmsg(self):
    def _newmsg(self):
        """Get started on a new message"""
        self.inheader=1  #Start off by reading the mail header
        selfmailto=[]
        self.lastheader=""
        msgheader=[] 
        msgbody=[]
    #}}} 
    #{{{def _linein(self,line):
    def _linein(self,line):
        value="" #The value of the header
        if self.inheader and not line.strip(): self.inheader=0
        if self.inheader:
            self.msgheader.append(line.strip()+"\n") #Make sure headers are short and unix text formatted
            hidx=line.find(":") #Find the header name
            if not line[0].strip()=="" and not hidx==-1:
                self.lastheader=line[:hidx]
                try: value=line[hidx+2:]
                except IndexError: value=""
            elif line[0].strip()=="": value=line
            if self.lastheader=="To": 
                for i in value.strip().split(','):
                    if i: self.mailto.append(self._toextract(i))
        else:
            self.msgbody.append(line)
    #}}}
    #{{{ def addheader(self,header,value):
    def addheader(self,header,value):
        """Add a header to the message"""
        if not value: return  #Skip blank headers
        self.msgheader.append(header.strip()+": "+value.strip()+"\n")
    #}}}
    #{{{def send(self):
    def send(self):
        """Send the message"""
        s=smtplib.SMTP(self.mailhost)
        try:
            s.sendmail(self.mailfrom,self.mailto,"".join(self.msgheader+self.msgbody))
        except smtplib.SMTPDataError:
            sys.stderr.write("Failed on :\n"+str(self.mailfrom)+"\n"+str(self.mailto)+"\n")
            raise
        s.quit() 
    #}}}
    #{{{def sendtest(self,showmsg=1):
    def sendtest(self,showmsg=1):
        """Send the message"""
        print "Sending from ",self.mailfrom,"to",self.mailto
        if showmsg: print "".join(self.msgheader+self.msgbody)
    #}}}
    def _toextract(self,to):
        r=re.compile("\<(?P<email>.*)\>")
        s=r.search(to)
        if s: to=s.group('email')
        return to


#}}}

s=Sendmailti()
s.mailhost="127.0.0.1"
s.read()
process=ApachePS().getps()
s.addheader("X-afrimail",process)
s.send()

#    vim600: sw=4 fdm=marker expandtab sm ts=3
