#!/usr/bin/env python3

import argparse
import datetime
import time
import email.utils
import subprocess
import pprint


def command(command: str) -> None:
    cmd = command.encode() + b"\n"
    subprocess.run(["xdotool", "type", "--file", "-"], input=cmd)
    time.sleep(2)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Generate SMTP messages to send a mail"
    )

    now = datetime.datetime.now()
    now_email = email.utils.formatdate(now.timestamp(), True)

    parser.add_argument("-s", "--sender", default="geoffrey@frogeye.fr")
    parser.add_argument("-r", "--receiver", default="geoffrey@frogeye.fr")
    parser.add_argument("-l", "--helo", default="frogeye.fr")
    parser.add_argument(
        "-o", "--subject", default=f"Test message {now.strftime('%H:%M:%S')}"
    )
    parser.add_argument("-m", "--me", default="Geoffrey")
    parser.add_argument("-g", "--gtube", action="store_true")
    parser.add_argument("-d", "--debug", action="store_true")
    parser.add_argument("-b", "--body", default="")


    args = parser.parse_args()

    if args.debug:
        command = print

    gtube = ""
    if args.gtube:
        gtube = """

XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X"""

    body = ""
    if args.body:
        body = f"\n\n{args.body}"


    text = f"""Date: {now_email}
From: {args.sender}
Subject: {args.subject}
To: {args.receiver}

Hello there,

This is a test message, generated from a template.
If you didn't expect to see this message, please contact {args.me}.{gtube}{body}

Greetings,

Input arguments:
{pprint.pformat(args, indent=4)}

-- 
{args.me}
."""

    if not args.debug:
        for i in range(3, 0, -1):
            print(f"Typing mail in {i}…")
            time.sleep(1)

    command(f"EHLO {args.helo}")
    command(f"MAIL FROM: <{args.sender}>")
    command(f"RCPT TO: <{args.receiver}>")
    command("DATA")
    command(text)
    command("QUIT")

    print("Done")

    # For reference:
    # command("RSET")
    # command("VRFY")
    # command("NOOP")
    # command("QUIT")