import paramiko
import time

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

def main():
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(HOST, username=USER, password=PASS)
        
        # 1. Check for PHP-FPM
        print("🔍 Checking for PHP-FPM service...")
        stdin, stdout, stderr = ssh.exec_command("systemctl list-units --type=service | grep php")
        fpm_out = stdout.read().decode()
        print(f"Service Check:\n{fpm_out}")
        
        if "fpm" in fpm_out:
            print("⚠️ PHP-FPM detected. Restarting it...")
            # Extract service name e.g. php8.4-fpm.service
            for line in fpm_out.splitlines():
                if "fpm" in line:
                    svc = line.split()[0]
                    print(f"   Restarting {svc}...")
                    ssh.exec_command(f"echo '{PASS}' | sudo -S systemctl restart {svc}")
        
        # 2. Create Web Check File
        check_code = "<?php echo 'WEB_IMAP_STATUS: ' . (function_exists('imap_open') ? 'OK' : 'MISSING'); ?>"
        cmd = f"echo \"{check_code}\" > /tmp/chk_imap.php && echo '{PASS}' | sudo -S mv /tmp/chk_imap.php {REMOTE_BASE}/public/chk_imap.php"
        ssh.exec_command(cmd)
        
        # 3. Test via Curl (Localhost on VPS)
        print("\n🔍 Testing IMAP via Web (curl localhost)...")
        stdin, stdout, stderr = ssh.exec_command(f"curl -s http://localhost/repondeur_mail_grok/public/chk_imap.php")
        web_response = stdout.read().decode()
        print(web_response)
        
        # Cleanup
        ssh.exec_command(f"echo '{PASS}' | sudo -S rm {REMOTE_BASE}/public/chk_imap.php")
        
        ssh.close()
    except Exception as e:
        print(f"❌ Error: {e}")

if __name__ == "__main__":
    main()
