import paramiko
import sys
import os
import time

HOST = "135.125.102.180"
USER = "ubuntu"
PASS = "BotPascal2026!"
LOCAL_FILE = "public/action.php"
REMOTE_FILE = "/var/www/html/repondeur_mail_grok/public/action.php"

def main():
    print("Waiting 3s cooldown...")
    time.sleep(3)
    
    ssh = None
    max_retries = 3
    for attempt in range(max_retries):
        try:
            print(f"Connecting to {HOST} (Attempt {attempt+1}/{max_retries})...")
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            # Increase banner timeout drastically
            ssh.connect(HOST, username=USER, password=PASS, banner_timeout=60, timeout=20)
            break
        except Exception as e:
            print(f"Connection failed: {e}")
            if attempt == max_retries - 1:
                print("Aborting.")
                return
            time.sleep(5)

    try:        
        # 1. Upload to /tmp
        tmp_remote = "/tmp/action.php"
        sftp = ssh.open_sftp()
        print(f"Uploading -> {tmp_remote}")
        sftp.put(os.path.abspath(LOCAL_FILE), tmp_remote)
        sftp.close()
        
        # 2. Sudo Move
        print("Moving to target...")
        ssh.exec_command(f"sudo mv {tmp_remote} {REMOTE_FILE}")
        ssh.exec_command(f"sudo chown www-data:www-data {REMOTE_FILE}")

        ssh.close()
        print("Backend Update Complete (Robust).")
    except Exception as e:
        print(f"Error during file op: {e}")

if __name__ == "__main__":
    main()
