#!/usr/bin/env python3
import base64
import sys
from pathlib import Path

import paramiko

sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(__file__).resolve().parents[1]
PASS = "Moli@5404"
REMOTE = "/home/morteza/torbatyar"


def main():
    c = paramiko.SSHClient()
    c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    c.connect("192.168.10.162", username="morteza", password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
    sftp = c.open_sftp()
    local = ROOT / "infrastructure/keycloak/themes/torbatyar/login/theme.properties"
    remote = f"{REMOTE}/infrastructure/keycloak/themes/torbatyar/login/theme.properties"
    sftp.put(str(local), remote)
    print("uploaded theme.properties")
    print(local.read_text(encoding="utf-8"))
    sftp.close()

    cmd = f"cd {REMOTE} && docker compose restart keycloak && sleep 8 && docker compose ps keycloak"
    b64 = base64.b64encode(cmd.encode()).decode()
    full = f"echo {PASS!r} | sudo -S -p '' bash -c 'echo {b64} | base64 -d | bash'"
    _, stdout, stderr = c.exec_command(full, timeout=120, get_pty=True)
    print((stdout.read() + stderr.read()).decode("utf-8", "replace"))
    c.close()


if __name__ == "__main__":
    main()
