#!/usr/bin/env python3

# Same CSV as used in creating email accounts

# CSV file structure:
# EMAIL_ACCOUNT EMAIL_PASSWORD_SRC EMAIL_HOST_SRC EMAIL_ADDRESS

# CSV field explanation
# EMAIL_ACCOUNT: Name of the old email account on the source server. i.e. wp1234567-mm
# EMAIL_PASSWORD_SRC: Password for the email account on the source server
# EMAIL_HOST_SRC: Hostname of the source server. i.e.  wp1234567.server-he.de
# EMAIL_ADDRESS: Primary email address for the account on the destination server. Must be unique and the domain must exist on the destination server

# General notes on CSV
# All fields in a row must be filled
# Delimiter is "€", since all other characters might be used in the passwords.
# Upper case letters may only be used in passwords

# Usage: 
# download script via wget to source server
# wget https://script.superpro.xyz/he_migration_cwh_fms_plesk/check_credentials_email_src.py
# run ./check_credentials_email_src.py -f /path/to/my.csv

import csv
import smtplib
import ssl
import argparse
# import time # import required if the wait further down should be used

def batch_smtp_test(csv_file):
    """
    Tests SMTP login credentials from a CSV file, ignoring the 4th column.

    Args:
        csv_file (str): Path to the CSV file containing credentials.

    Returns:
        tuple: A tuple containing two lists: successful_logins and failed_logins.
    """

    SUCCESSFUL_LOGINS = []
    FAILED_LOGINS = []

    try:
        with open(csv_file, 'r', newline='') as file:
            reader = csv.reader(file, delimiter='€')
            next(reader, None)  # Skip the header row if present
            for row in reader:
                if len(row) < 3:  # Check for at least 3 columns
                    print("Warning: Insufficient columns in row: {}".format(row))
                    continue

                EMAIL_ACCOUNT, EMAIL_PASSWORD_SRC, EMAIL_HOST_SRC = row[0], row[1], row[2]  # Extract values
                try:
                    EMAIL_ACCOUNT = EMAIL_ACCOUNT.lower()
                    context = ssl.create_default_context()
                    with smtplib.SMTP_SSL(EMAIL_HOST_SRC, 465, context=context) as server: #Or use 587 and starttls
                        server.login(EMAIL_ACCOUNT, EMAIL_PASSWORD_SRC)
                        SUCCESSFUL_LOGINS.append((EMAIL_ACCOUNT, EMAIL_PASSWORD_SRC, EMAIL_HOST_SRC))
                        print("Success: {}@{}".format(EMAIL_ACCOUNT, EMAIL_HOST_SRC))

                except Exception as e:
                    FAILED_LOGINS.append((EMAIL_ACCOUNT, EMAIL_PASSWORD_SRC, EMAIL_HOST_SRC, str(e)))
                    print("Failed: {}@{} - {}".format(EMAIL_ACCOUNT, EMAIL_HOST_SRC, e))

#                time.sleep(2) # Hardcoded 2 second wait time

    except FileNotFoundError:
        print("Error: File not found: {}".format(csv_file))

    return SUCCESSFUL_LOGINS, FAILED_LOGINS

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Batch test SMTP login credentials from a CSV file.")
    parser.add_argument("-f", "--file", required=True, help="Path to the CSV file.")
    args = parser.parse_args()

    csv_file_path = args.file
    SUCCESSFUL, FAILED = batch_smtp_test(csv_file_path)

    print("\nSuccessful Logins:")
    for EMAIL_ACCOUNT, EMAIL_PASSWORD_SRC, EMAIL_HOST_SRC in SUCCESSFUL:
        print("EMAIL_ACCOUNT: {}, Host: {}".format(EMAIL_ACCOUNT, EMAIL_HOST_SRC))

    print("\nFailed Logins:")
    for EMAIL_ACCOUNT, EMAIL_PASSWORD_SRC, EMAIL_HOST_SRC, ERROR in FAILED:
        print("EMAIL_ACCOUNT: {}, Host: {}, Error: {}".format(EMAIL_ACCOUNT, EMAIL_HOST_SRC, ERROR))

