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

import paramiko

sys.stdout.reconfigure(encoding="utf-8", errors="replace")
PASS = "Moli@5404"


def run(cmd, sudo=True):
    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,
    )
    if sudo:
        b64 = base64.b64encode(cmd.encode()).decode()
        full = f"echo {PASS!r} | 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[-12000:] if len(text) > 12000 else text)
    c.close()


run(
    """
cd /home/morteza/torbatyar
echo '===== POST mobile/start ====='
curl -sS -m 20 -i -X POST http://127.0.0.1:8001/api/v1/auth/mobile/start \
  -H 'Content-Type: application/json' \
  -H 'Origin: https://torbatyar.ir' \
  -d '{"mobile":"09155105404","context":"public"}'
echo
echo '===== identity logs ====='
docker compose logs --tail=120 identity-access-service 2>&1 | tail -n 120
echo '===== core otp related ====='
docker compose logs --tail=80 core-service 2>&1 | tail -n 80
"""
)
