#!/usr/bin/env python
#
# Copyright (c) 2015, Arista Networks, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#   Redistributions of source code must retain the above copyright notice,
#   this list of conditions and the following disclaimer.
#
#   Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
#
#   Neither the name of Arista Networks nor the names of its
#   contributors may be used to endorse or promote products derived from
#   this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# pylint: disable=C0209

import io
import os
import smtplib
from email import encoders as Encoders
from email.mime import base as MIMEBase
from email.mime import multipart as MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate


def send_message(smarthost, sender, receivers, msg):
    smtp = smtplib.SMTP(smarthost)
    smtp.sendmail(sender, COMMASPACE.join(receivers), msg.as_string())
    smtp.close()


def run_command(command, node):
    command = command.strip()
    output = node.api_enable_cmds([command], text_format=True)
    filename = str(command).replace(" ", "_")
    with io.open(filename, "w", encoding="utf8") as fd:
        fd.write(" ".join(output))
    return filename


def main(attributes):
    """Sends an email using an SMTP relay host

    Generates an email from the bootstrap process and routes it through a
    smarthost.  The parameters value expects a dictionary with the
    following values in order for this function to work properly.
    ::

        {
            'smarthost':   <hostname of smarthost>,
            'sender':      <from email address>
            'receivers':   [ <array of recipients to send email to> ],
            'subject':     <subject line of the message>,
            'body':        <the message body>,
            'attachments': [ <array of files to attach> ],
            'commands':    [ <array of commands to run and attach> ]
        }

    The required fields for this function are smarthost, sender, and
    receivers. All other fields are optional.

    This action is dual-supervisor compatible.

    Args:
        attributes (list): list of attributes; use attributes.get(<ATTRIBUTE_NAME>)
                            to read attribute values
        node (internal): attributes.get('NODE') API: see documentation
        smarthost: hostname of smarthos>,
        sender: from email addres>
        receivers: [ <array of recipients to send email to> ]
        subject: subject line of the message
        body: the message body
        attachments: [ <array of files to attach> ]
        commands: [ <array of commands to run and attach> ]

    Example:
        ::

            -
              action: send_mail
              attributes:
                  smarthost: smtp.example.com
                  from: noreply@example.com
                  subject: This is a test message from a switch in ZTP
                  receivers:
                      bob@exmple.com
                      helen@example.com
                  body: Please see the attached 'show version'
                  commands: show version

    """

    node = attributes.get("NODE")

    smarthost = attributes.get("smarthost")
    if not smarthost:
        raise RuntimeError("Missing attribute('smarthost')")

    sender = attributes.get("sender")
    if not sender:
        raise RuntimeError("Missing attribute('sender')")

    receivers = attributes.get("receivers")
    if not receivers:
        raise RuntimeError("Missing attribute('receivers')")

    msg = MIMEMultipart.MIMEMultipart()
    msg["From"] = sender
    msg["To"] = COMMASPACE.join(receivers)
    msg["Date"] = formatdate(localtime=True)
    msg["Subject"] = attributes.get("subject") or "ZTP Bootstrap"

    body = attributes.get("body", "empty-body")
    attachments = attributes.get("attachments", [])
    commands = attributes.get("commands", [])

    attributes.get("NODE").log_msg("Running commands: {}".format(str(commands)))
    if commands:
        body += "\nThe output from the following commmands have been added as attachments:"
        for command in commands:
            filename = run_command(command, node)
            attachments.append(filename)
            body += "\n\t* {} ({})".format(command, filename)

    attributes.get("NODE").log_msg("Collecting attachments: {}".format(str(attachments)))
    if attachments:
        for filename in attachments:
            if os.path.exists(filename):
                filename = filename.strip()
                part = MIMEBase.MIMEBase("application", "octet-stream")
                with io.open(filename, "rb", encoding="utf8") as fd:
                    part.set_payload(fd.read())
                Encoders.encode_base64(part)
                part.add_header(
                    "Content-Disposition",
                    "attachment; filename='{}'".format(os.path.basename(filename)),
                )
                attributes.get("NODE").log_msg("Attaching {}".format(filename))
                msg.attach(part)

    msg.attach(MIMEText(body))

    attributes.get("NODE").log_msg("Sending email using smarthost {}".format(smarthost))
    send_message(smarthost, sender, receivers, msg)
