#!/usr/bin/env python3
from __future__ import annotations

#   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 print_usage() -> None:
    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("")


MIN_ARGS = 2

if len(sys.argv) < MIN_ARGS:
    print_usage()
    sys.exit(1)

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

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

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

# read message
try:
    with open(sys.argv[1], 'rb') as fh:
        message = fh.read()
except FileNotFoundError:
    print("")
    print(f"File '{sys.argv[1]}' not found")
    print_usage()
    smtp_server.quit()
    sys.exit(1)

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

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

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