import paramiko
import sys
import os

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

FILES_TO_DEPLOY = [
    # Scripts
    ("scripts/scan_loop.php", "/var/www/html/repondeur_mail_grok/scripts/scan_loop.php"),
    # Pages
    ("public/index.php", "/var/www/html/repondeur_mail_grok/public/index.php"),
    ("public/action.php", "/var/www/html/repondeur_mail_grok/public/action.php"),
    ("public/spam.php", "/var/www/html/repondeur_mail_grok/public/spam.php"),
    ("public/suspicion.php", "/var/www/html/repondeur_mail_grok/public/suspicion.php"),
    ("public/tags.php", "/var/www/html/repondeur_mail_grok/public/tags.php"),
    # Includes
    ("public/includes/header.php", "/var/www/html/repondeur_mail_grok/public/includes/header.php"),
    ("public/includes/nav.php", "/var/www/html/repondeur_mail_grok/public/includes/nav.php"),
    ("public/includes/footer.php", "/var/www/html/repondeur_mail_grok/public/includes/footer.php"),
    # Core
    ("core/ImapClient.php", "/var/www/html/repondeur_mail_grok/core/ImapClient.php"),
]

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

        # Ensure remote includes dir exists
        print("Ensuring remote directories exist...")
        ssh.exec_command("sudo mkdir -p /var/www/html/repondeur_mail_grok/public/includes")
        ssh.exec_command("sudo chown -R ubuntu:ubuntu /var/www/html/repondeur_mail_grok/public")

        for local_path, remote_path in FILES_TO_DEPLOY:
            if not os.path.exists(local_path):
                print(f"❌ Local file missing: {local_path}")
                continue
            
            print(f"Uploading {local_path} -> {remote_path}...")
            # Upload to tmp first to avoid permission issues if ownership wrong
            tmp_path = "/tmp/" + os.path.basename(local_path)
            sftp.put(local_path, tmp_path)
            
            # Sudo move
            ssh.exec_command(f"sudo mv {tmp_path} {remote_path}")
            ssh.exec_command(f"sudo chown www-data:www-data {remote_path}")

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

if __name__ == "__main__":
    main()
