import paramiko
import sys

# CONFIG
HOST = "135.125.102.180"
USER = "ubuntu"
PASS = "BotPascal2026!"

def run_sudo(ssh, command, password):
    print(f"Running: {command}")
    cmd = f"echo '{password}' | sudo -S {command}"
    stdin, stdout, stderr = ssh.exec_command(cmd)
    # Read output to ensure completion
    print(stdout.read().decode())
    err = stderr.read().decode()
    if err and "password" not in err.lower():
        print(f"STDERR: {err}")

def main():
    print(f"Connecting to {HOST}...")
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(HOST, username=USER, password=PASS)
        
        # 1. Update APT
        run_sudo(ssh, "apt-get update", PASS)
        
        # 2. Install PHP IMAP
        # Detect PHP version just in case, or just install generic 'php-imap' which maps to current.
        run_sudo(ssh, "apt-get install -y php-imap", PASS)
        
        # 3. Enable module
        run_sudo(ssh, "phpenmod imap", PASS)
        
        # 4. Restart Apache (and PHP-FPM if exists, but Apache usually handles mod_php)
        run_sudo(ssh, "service apache2 restart", PASS)
        
        # 5. Verify
        print("Verifying installation...")
        stdin, stdout, stderr = ssh.exec_command("php -m | grep imap")
        if "imap" in stdout.read().decode():
            print("✅ PHP IMAP Installed Successfully.")
        else:
            print("❌ Installation seemed to fail.")

        ssh.close()
        
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()
