#!/usr/bin/env python3
import base64
import sys

import paramiko

sys.stdout.reconfigure(encoding="utf-8", errors="replace")


def run(cmd, sudo=False):
    c = paramiko.SSHClient()
    c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    c.connect(
        "192.168.10.162",
        username="morteza",
        password="Moli@5404",
        timeout=30,
        allow_agent=False,
        look_for_keys=False,
    )
    if sudo:
        b64 = base64.b64encode(cmd.encode()).decode()
        full = f"echo 'Moli@5404' | sudo -S -p '' bash -c 'echo {b64} | base64 -d | bash'"
    else:
        full = f"bash -lc {cmd!r}"
    _, stdout, stderr = c.exec_command(full, timeout=120, get_pty=True)
    text = (stdout.read() + stderr.read()).decode("utf-8", "replace")
    print(text[-10000:] if len(text) > 10000 else text)
    c.close()


run(
    """
cd /home/morteza/torbatyar
docker compose logs --tail=100 identity-access-service
echo '===== CURL ====='
curl -sS -m 15 -X POST http://127.0.0.1:8001/api/v1/auth/mobile/start \
  -H 'Content-Type: application/json' \
  -d '{"mobile":"09155105404","context":"public"}'
echo
""",
    sudo=True,
)
