#!/usr/bin/env python3
"""Upload Servidor/mail to VPS (PHP email API for web + gamemode)."""
import sys
from pathlib import Path

import paramiko
from scp import SCPClient

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from deploy_vps import VPS_HOST, VPS_PASS, VPS_USER  # noqa: E402

# Nginx root for models.hostlanty.com is /var/www/servidor (see mail/nginx-models.hostlanty.com.conf)
REMOTE_DIR = "/var/www/servidor/mail"
LOCAL_DIR = Path(__file__).resolve().parent.parent / "Servidor" / "mail"
FILES = ["config.php", "template.php", "send.php", "smtp.php"]


def main():
    if not LOCAL_DIR.exists():
        raise SystemExit(f"Local mail dir not found: {LOCAL_DIR}")

    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    print(f"Connecting to {VPS_HOST}...")
    client.connect(VPS_HOST, username=VPS_USER, password=VPS_PASS, timeout=30)

    run = client.exec_command(f"mkdir -p '{REMOTE_DIR}'")
    run[1].channel.recv_exit_status()

    with SCPClient(client.get_transport()) as scp:
        for name in FILES:
            local_path = LOCAL_DIR / name
            if not local_path.exists():
                print(f"Skipping missing file: {name}")
                continue
            remote_path = f"{REMOTE_DIR}/{name}"
            print(f"Uploading {name} -> {remote_path}")
            scp.put(str(local_path), remote_path)

    client.exec_command(
        f"chmod 640 '{REMOTE_DIR}/config.php' && "
        f"chmod 644 '{REMOTE_DIR}/template.php' '{REMOTE_DIR}/send.php' '{REMOTE_DIR}/smtp.php'"
    )

    _, stdout, _ = client.exec_command(
        f"php -r \"require '{REMOTE_DIR}/config.php'; echo 'mail config ok';\" 2>&1"
    )
    out = stdout.read().decode("utf-8", errors="replace").strip()
    if out:
        print(out)

    client.close()
    print("Mail files uploaded to", REMOTE_DIR)


if __name__ == "__main__":
    main()
