import paramiko
import os

host = '192.168.178.153'
user = 'hitonabi'
password = 'Tu77ceu2zzvx!'

print("Connecting to server...")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=password, look_for_keys=False, allow_agent=False)

print("Uploading update.tar.gz...")
sftp = ssh.open_sftp()
sftp.put('update.tar.gz', '/home/hitonabi/update.tar.gz')
sftp.close()

commands = [
    # Extrahiere das Update
    "cd /home/hitonabi/mission-control && tar -xzf /home/hitonabi/update.tar.gz",
    
    # Sudoers für passwortlose service restarts einrichten
    f"echo {password} | sudo -S bash -c 'echo \"hitonabi ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart mission-control, /usr/bin/systemctl restart llama-swap, /usr/bin/journalctl\" > /etc/sudoers.d/mission-control'",
    f"echo {password} | sudo -S chmod 440 /etc/sudoers.d/mission-control",
    
    # Neustart des Dienstes
    f"echo {password} | sudo -S systemctl restart mission-control"
]

for cmd in commands:
    print(f"Executing: {cmd}")
    stdin, stdout, stderr = ssh.exec_command(cmd)
    exit_status = stdout.channel.recv_exit_status()
    print("STDOUT:", stdout.read().decode())
    print("STDERR:", stderr.read().decode())
    if exit_status != 0:
        print(f"Error executing {cmd}")

ssh.close()
print("Deployment complete!")
