import paramiko
import os
from datetime import datetime

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

def main():
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(HOST, username=USER, password=PASS)
        
        # Create backup dir if not exists
        ssh.exec_command(f"mkdir -p {BACKUP_DIR}")
        
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_filename = f"backup_repondeur_{timestamp}.tar.gz"
        backup_path = f"{BACKUP_DIR}/{backup_filename}"
        
        print(f"📦 Création de la sauvegarde {backup_filename}...")
        
        # Tar command (exclude logs maybe? verify user intent. keeping simple: full backup)
        # Exclude huge logs if any? 100MB logs ok
        cmd = f"sudo tar -czf {backup_path} -C /var/www/html repondeur_mail_grok"
        
        stdin, stdout, stderr = ssh.exec_command(cmd)
        err = stderr.read().decode()
        if err:
            print(f"⚠️ Warning/Error: {err}")
            
        # Check size
        stdin, stdout, stderr = ssh.exec_command(f"ls -lh {backup_path}")
        print(stdout.read().decode().strip())
        
        print(f"\n✅ Sauvegarde terminée sur le VPS: {backup_path}")
        
        ssh.close()
        
    except Exception as e:
        print(f"❌ Error: {e}")

if __name__ == "__main__":
    main()
