#!/usr/bin/env python

#   Copyright 2013 Oli Schacher
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


# This tool is used to send messages to the fuglu debug port

import smtplib
import sys
import ConfigParser

if len(sys.argv)<2:
    print ""
    print "Usage fuglu_debug <messagefile> [ <envelope_from> [ <envelope_to ] ]"
    print "<messagefile> : Message content to be sent to the fuglu debug port"
    print "<envelope_from> : Envelope From Address, default sender@fuglu.local"
    print "<envelope_to> : Envelope To Address, default recipient@fuglu.local"
    print ""
    
    sys.exit(1)

# what port is fuglu debugging?
fugluconfigfile='/etc/fuglu/fuglu.conf'
newconfig=ConfigParser.ConfigParser()
readconfig=newconfig.read([fugluconfigfile])

try:
    localport=newconfig.getint('debug','debugport')
except:
    localport=10888    

#connect to debug port
smtpServer = smtplib.SMTP('127.0.0.1',localport)
smtpServer.set_debuglevel(1)
smtpServer.helo('fuglu.debug.local')

#read message
fh=open(sys.argv[1])
message=fh.read()

#envelope sender/recipient
fromaddr='sender@fuglu.local'
toaddr='recipient@fuglu.local'

if len(sys.argv)>2:
    fromaddr=sys.argv[2]
if len(sys.argv)>3:
    toaddr=sys.argv[3]

#off we go
smtpServer.sendmail(fromaddr, toaddr, message)
smtpServer.quit()