#!/usr/bin/env python3
"""Minimal SMTP listener used as a TCP egress probe for the iDRAC.

    python smtp_probe.py --port 2525

Logs every connection and SMTP command to smtp.log, so `racadm testemail`
proves whether the iDRAC can open an outbound TCP connection to this PC.
"""
import argparse
import datetime
import os
import socket
import threading

HERE = os.path.dirname(os.path.abspath(__file__))
LOG = os.path.join(HERE, "smtp.log")


def log(line):
    stamp = datetime.datetime.now().strftime("%H:%M:%S")
    line = f"[{stamp}] {line}"
    print(line, flush=True)
    with open(LOG, "a", encoding="utf-8") as fh:
        fh.write(line + "\n")


def handle(conn, addr):
    log(f"CONNECT {addr[0]}:{addr[1]}")
    try:
        conn.sendall(b"220 probe ESMTP\r\n")
        buf = b""
        data_mode = False
        while True:
            chunk = conn.recv(4096)
            if not chunk:
                break
            buf += chunk
            while b"\n" in buf:
                line, buf = buf.split(b"\n", 1)
                text = line.rstrip(b"\r").decode("utf-8", "replace")
                if data_mode:
                    if text == ".":
                        data_mode = False
                        conn.sendall(b"250 OK\r\n")
                    else:
                        log(f"DATA {text[:200]}")
                    continue
                if not text:
                    continue
                log(f"CMD {text[:200]}")
                verb = text.split(" ", 1)[0].upper()
                if verb in ("EHLO", "HELO"):
                    conn.sendall(b"250-probe\r\n250 OK\r\n")
                elif verb == "MAIL":
                    conn.sendall(b"250 OK\r\n")
                elif verb == "RCPT":
                    conn.sendall(b"250 OK\r\n")
                elif verb == "DATA":
                    data_mode = True
                    conn.sendall(b"354 End data with <CR><LF>.<CR><LF>\r\n")
                elif verb == "QUIT":
                    conn.sendall(b"221 Bye\r\n")
                    return
                else:
                    conn.sendall(b"250 OK\r\n")
    except Exception as e:
        log(f"ERROR {e!r}")
    finally:
        try:
            conn.close()
        except Exception:
            pass
        log(f"CLOSE {addr[0]}:{addr[1]}")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, default=2525)
    ap.add_argument("--bind", default="0.0.0.0")
    a = ap.parse_args()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((a.bind, a.port))
    s.listen(16)
    print(f"smtp probe on {a.bind}:{a.port} -> {LOG}", flush=True)
    while True:
        conn, addr = s.accept()
        threading.Thread(target=handle, args=(conn, addr), daemon=True).start()


if __name__ == "__main__":
    main()
