import paramiko
import os

HOST = "135.125.102.180"
USER = "ubuntu"
PASS = "BotPascal2026!"
REMOTE_BASE = "/var/www/html/repondeur_mail_grok"

FILES_TO_UPLOAD = [
    ("public/index.php", "public/index.php"),
    ("public/action.php", "public/action.php"),
    ("scripts/scan.php", "scripts/scan.php"),
    ("scripts/scan_loop.php", "scripts/scan_loop.php")
]

def main():
    try:
        print(f"🔌 Connecting to {HOST}...")
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(HOST, username=USER, password=PASS)
        sftp = ssh.open_sftp()
        print("✅ Connected.")

        # 1. Diagnose and Install
        print("🔍 Checking PHP version on VPS...")
        stdin, stdout, stderr = ssh.exec_command("php -v")
        print(stdout.read().decode())
        
        print("🔍 Searching for php-imap packages...")
        stdin, stdout, stderr = ssh.exec_command("echo 'BotPascal2026!' | sudo -S apt-cache search php | grep imap")
        print(stdout.read().decode())

        print("📦 Attempting to install generic php-imap...")
        # Try generic php-imap which usually points to default version
        install_cmd = f"echo '{PASS}' | sudo -S apt-get update && echo '{PASS}' | sudo -S apt-get install -y php-imap"
        stdin, stdout, stderr = ssh.exec_command(install_cmd)
        
        output = stdout.read().decode()
        error = stderr.read().decode()
        print(output)
        if error:
            print(f"⚠️  StdErr: {error}")

        # 2. Upload Files via TMP (to bypass permission issues)
        print("\n📤 Uploading modified files (via /tmp)...")
        
        for local_rel, remote_rel in FILES_TO_UPLOAD:
            # Local path
            local_path = f"/home/dan/Documents🤮/🔴2026🔴/🔴----ROBOT-WHATSAPP-MARCHE-GroK----🔴/✍️ REPONDEUR_MAIL_GROK/{local_rel}"
            # Remote tmp path
            filename = os.path.basename(local_rel)
            remote_tmp = f"/tmp/{filename}"
            remote_dest = f"{REMOTE_BASE}/{remote_rel}"
            
            print(f"   - {local_rel} -> {remote_tmp} -> {remote_dest}")
            sftp.put(local_path, remote_tmp)
            
            # Sudo move and perm
            cmd = f"echo '{PASS}' | sudo -S cp {remote_tmp} {remote_dest} && echo '{PASS}' | sudo -S chmod 644 {remote_dest} && echo '{PASS}' | sudo -S chown www-data:www-data {remote_dest}"
            stdin, stdout, stderr = ssh.exec_command(cmd)
            err = stderr.read().decode()
            if err:
                 print(f"     ⚠️ {err}")

        print("✅ Upload complete.")
        
        # 3. Enable Module and Restart
        print("\n🔧 Enabling IMAP module...")
        ssh.exec_command(f"echo '{PASS}' | sudo -S phpenmod imap")
        
        print("🔍 Verifying IMAP module...")
        stdin, stdout, stderr = ssh.exec_command("php -m | grep imap")
        print(f"   > {stdout.read().decode().strip()}")

        print("\n🔄 Restarting Apache...")
        ssh.exec_command(f"echo '{PASS}' | sudo -S systemctl restart apache2")
        print("✅ Apache restarted.")

        ssh.close()
        print("\n🚀 DEPLOYMENT SUCCESSFUL!")

    except Exception as e:
        print(f"\n❌ Error: {e}")

if __name__ == "__main__":
    main()
