#!/usr/bin/python
#
# Copyright: OpenFW (c) 2006
# License: GPL
# Date: 04.02.2006
#

from sys import exit
from sys import stdin
import os
import re
import tempfile

from endian.core.logger import *
from optparse import OptionParser
from endian.core.mailfile import MailSender

SETTINGS_CONF = '/etc/notifications/settings.conf'


def get_from_addr_from_settings():
    """Read from_addr from /etc/notifications/settings.conf if present."""
    if not os.path.exists(SETTINGS_CONF):
        return None
    # settings.conf is a simple key = value file (not INI sections)
    from_addr = None
    with open(SETTINGS_CONF) as f:
        for line in f:
            line = line.strip()
            if line.startswith('from_addr'):
                parts = line.split('=', 1)
                if len(parts) == 2:
                    from_addr = parts[1].strip()
                    break
    return from_addr


def substitute_from_addr(template_content, from_addr):
    """Replace the sender email in the From: header with the real sender email from settings.conf."""
    if not from_addr:
        return template_content
    # Match From: Name <email> and replace the email part with from_addr from settings
    pattern = r'^(From:\s*[^\n<]*<)[^>]+>(.*)$'
    replacement = r'\g<1>' + from_addr + r'>\g<2>'
    result = re.sub(pattern, replacement, template_content, flags=re.MULTILINE)
    return result


def get_text():
    print 'Enter Text, end with ctrl + D'
    msg = ''
    while 1:
        try:
            line = raw_input()
        except EOFError:
            break
        if line == None:
            break
        msg = '%s\n%s' % (msg, line)
    print 'Text saved!'
    return msg


if __name__=='__main__':
    parser = OptionParser()
    parser.add_option("-t", "--to", dest="to_addr", help="Send mail to MAIL", metavar="MAIL")
    parser.add_option("-f", "--from", dest="from_addr", help="Set sender e-mail to MAIL (default: root@localhost)", metavar="MAIL", default="root@localhost")
    parser.add_option("-m", "--mailserver", dest="mailhost", help="SMTP server to use (default: localhost)", default="localhost")
    parser.add_option("-a", "--attachment", dest="filename", help="Attachement")
    parser.add_option("-s", "--subject", dest="subject", help="Subject")
    parser.add_option("-v", "--text", dest="text", help="Body text, if you do not use cheetah and stdin")
    parser.add_option("-b", "--body", dest="body", help="Body cheetah template")
    parser.add_option("-M", "--mailtemplate", dest="mailtemplate", help="Full mail cheetah template")
    parser.add_option("-D", "--variables", dest="variables", type="string",
                      help="Space-separated list of KEY=VALUE pairs, which represent "
                      "substitution values for cheetah templates. If VALUE is "
                      "file:FILENAME the content is read out from file FILENAME.")
    parser.add_option("-S", "--variables-stdin", dest="variablesstdin",
                      action="store_true",
                      help="Read substitution values for cheetah templates as list "
                      "of KEY=VALUE pairs from stdin")
    parser.add_option("-d", "--debug", dest="debug",
                      action="store_true",
                      help="be more verbose", default=False)
    parser.add_option("-c", "--caller", dest="caller", metavar="CALLER",
                      help="add CALLER to log lines", default=False)

    (options, args) = parser.parse_args()

    if options.debug:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    if (options.variablesstdin and
            options.body == None and
            options.text == None and
            options.mailtemplate == None):
        error("--variables-stdin cannot be read out "
              "from stdin when mail body will be read out"
              "from stdin.")
        parser.print_help()
        exit(1)

    if not options.to_addr:
        error("No destination e-mail set")
        parser.print_help()
        exit(1)

    if options.body == None and options.text == None and options.mailtemplate == None:
        options.text = get_text()
    elif options.variablesstdin:
        debug("Read variables from stdin")
        tmp = " ".join(stdin.readlines())
        options.variables = str(options.variables) + " " + tmp.replace("\n", " ")

    caller = ""
    if options.caller:
        caller = " Mail caller: '%s'" % options.caller

    # Resolve sender email: CLI option takes precedence, otherwise settings.conf
    settings_from_addr = get_from_addr_from_settings()
    sender_email = options.from_addr if options.from_addr != 'root@localhost' else settings_from_addr

    # If a mailtemplate file is provided, read it, substitute the From: sender
    # email with from_addr from settings.conf, write to a temp file and pass
    # that as mailtemplate so MailSender processes it as a Cheetah template.
    mailtemplate = options.mailtemplate
    if mailtemplate and os.path.exists(mailtemplate):
        with open(mailtemplate) as f:
            tmpl_content = f.read()
        tmpl_content = substitute_from_addr(tmpl_content, sender_email)
        # Write substituted content to a temp file so MailSender can open it
        tmpfd, tmppath = tempfile.mkstemp(suffix='.mail.tmpl', prefix='mailfile-')
        try:
            os.write(tmpfd, tmpl_content)
            os.close(tmpfd)
            mailtemplate = tmppath
        except:
            os.close(tmpfd)
            os.unlink(tmppath)
            raise

    ms = MailSender(sender_email or options.from_addr, options.to_addr, options.mailhost, caller)
    ms.sendmail(
        subject=options.subject,
        attachment=options.filename,
        text=options.text,
        cheetah_body=options.body,
        mailtemplate= mailtemplate,
        variables=options.variables
    )

    # Clean up temp file if we created one
    if options.mailtemplate and os.path.exists(mailtemplate) and mailtemplate != options.mailtemplate:
        try:
            os.unlink(mailtemplate)
        except:
            pass
