import paramiko
import sys
import os

HOST = "135.125.102.180"
USER = "ubuntu"
PASS = "BotPascal2026!"
LOCAL_FILE = "core/ImapClient.php"
REMOTE_TMP = "/tmp/ImapClient.php"
TARGET_FILE = "/var/www/html/repondeur_mail_grok/core/ImapClient.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)
        
        # 1. Upload to /tmp
        sftp = ssh.open_sftp()
        local_path = os.path.abspath(LOCAL_FILE)
        print(f"Uploading {local_path} -> {REMOTE_TMP}")
        sftp.put(local_path, REMOTE_TMP)
        sftp.close()
        
        # 2. Sudo Move and Chown
        print("Moving to target...")
        cmds = [
            f"sudo mv {REMOTE_TMP} {TARGET_FILE}",
            f"sudo chown www-data:www-data {TARGET_FILE}",
            f"sudo chmod 755 {TARGET_FILE}"
        ]
        
        for cmd in cmds:
            print(f"Exec: {cmd}")
            stdin, stdout, stderr = ssh.exec_command(cmd)
            err = stderr.read().decode()
            if err:
                print(f"STDERR: {err}")
            
        ssh.close()
        print("Deployment Complete via Sudo.")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()
