#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

#   Copyright Oli Schacher, Fumail Project
#
# 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


def printUsage():
    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("")


if len(sys.argv) < 2:
    printUsage()
    sys.exit(1)

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

try:
    localport = newconfig.getint('debug', 'debugport')
except Exception:
    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
try:
   fh = open(sys.argv[1],'rb')
   message = fh.read()
except FileNotFoundError:
    print("")
    print("File '%s' not found" % str(sys.argv[1]))
    printUsage()
    smtpServer.quit()
    sys.exit(1)

# 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()
