import paramiko
import stat

HOST = "192.168.1.50"
USER = "root"
PASSWORD = "Vlado7309208104++"
SCRIPT_NAME = "CollectPictures"
REMOTE_BASE = f"/boot/config/plugins/user.scripts/scripts/{SCRIPT_NAME}"
REMOTE_PY = f"{REMOTE_BASE}/collect_pictures.py"
REMOTE_SCRIPT = f"{REMOTE_BASE}/script"
LOCAL_SCRIPT = "00 PictureCollector/collect_pictures.py"

BASH_WRAPPER = """#!/bin/bash
python3 -u /boot/config/plugins/user.scripts/scripts/CollectPictures/collect_pictures.py
"""

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(HOST, username=USER, password=PASSWORD, look_for_keys=False, allow_agent=False)

def run(cmd):
    _, stdout, stderr = client.exec_command(cmd)
    out = stdout.read().decode().strip()
    err = stderr.read().decode().strip()
    if out: print(out)
    if err: print(f"[err] {err}")

run(f"mkdir -p {REMOTE_BASE}")

sftp = client.open_sftp()
sftp.put(LOCAL_SCRIPT, REMOTE_PY)
sftp.chmod(REMOTE_PY, stat.S_IRUSR | stat.S_IWUSR)
print(f"Python skript: {REMOTE_PY}")

with sftp.open(REMOTE_SCRIPT, "w") as f:
    f.write(BASH_WRAPPER)
sftp.chmod(REMOTE_SCRIPT, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP)
print(f"Bash wrapper:  {REMOTE_SCRIPT}")

with sftp.open(f"{REMOTE_BASE}/name", "w") as f:
    f.write("CollectPictures")
sftp.close()

print("\n--- Vysledek ---")
run(f"ls -la {REMOTE_BASE}/")
run(f"cat {REMOTE_SCRIPT}")

client.close()
print("Hotovo.")
