#!/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()
    sftp.put(str(ROOT / "docker-compose.yml"), f"{REMOTE}/docker-compose.yml")
    sftp.close()

    cmd = f"""
cd {REMOTE}
# reset only identity DB schema
docker exec superapp_postgres psql -U superapp -d identity_access_db -c 'DROP SCHEMA public CASCADE; CREATE SCHEMA public; GRANT ALL ON SCHEMA public TO superapp; GRANT ALL ON SCHEMA public TO public;'
docker compose up -d --force-recreate identity-access-service
sleep 20
docker compose logs --tail=40 identity-access-service
echo '===== tables ====='
docker exec superapp_postgres psql -U superapp -d identity_access_db -c '\\dt'
echo '===== test mobile/start ====='
curl -sS -m 30 -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 '===== via nginx ====='
curl -sk -m 30 -X POST https://identity.torbatyar.ir/api/v1/auth/mobile/start \
  --resolve identity.torbatyar.ir:443:192.168.10.156 \
  -H 'Content-Type: application/json' \
  -H 'Origin: https://torbatyar.ir' \
  -d '{{"mobile":"09155105404","context":"public"}}'
echo
"""
    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=300, get_pty=True)
    print((stdout.read() + stderr.read()).decode("utf-8", "replace")[-12000:])
    c.close()


if __name__ == "__main__":
    main()
