#!/usr/bin/env python3
"""Deploy Enamad verification (file + meta/title + nginx)."""
from __future__ import annotations

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"
APP = "192.168.10.162"
NGX = "192.168.10.156"


def connect(host, user):
    c = paramiko.SSHClient()
    c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    c.connect(host, username=user, password=PASS, timeout=30, allow_agent=False, look_for_keys=False)
    return c


def run(client, cmd, *, sudo=False, timeout=180):
    cmd = cmd.replace("\r\n", "\n").replace("\r", "\n").strip() + "\n"
    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 = client.exec_command(full, timeout=timeout, get_pty=True)
    text = (stdout.read() + stderr.read()).decode("utf-8", "replace")
    print(text[-5000:] if len(text) > 5000 else text)
    return text


def main():
    app = connect(APP, "morteza")
    sftp = app.open_sftp()
    sftp.put(str(ROOT / "frontend/public/78473978.txt"), "/home/morteza/torbatyar/frontend/public/78473978.txt")
    sftp.put(str(ROOT / "frontend/app/layout.tsx"), "/home/morteza/torbatyar/frontend/app/layout.tsx")
    sftp.close()
    run(
        app,
        "cd /home/morteza/torbatyar && docker compose restart frontend && sleep 8 && curl -sS -m 10 -o /dev/null -w fe=%{http_code} http://127.0.0.1:3000/78473978.txt && echo && curl -sS -m 15 http://127.0.0.1:3000/ | tr -d '\\r' | grep -E 'enamad|78473978' | head -n 10",
        sudo=True,
        timeout=120,
    )
    app.close()

    ngx = connect(NGX, "torbatyaruser")
    conf = (ROOT / "infrastructure/nginx/torbatyar.ir.conf").read_text(encoding="utf-8")
    b64 = base64.b64encode(conf.encode()).decode()
    run(
        ngx,
        f"echo {b64} | base64 -d > /etc/nginx/conf.d/torbatyar.ir.conf && nginx -t && systemctl reload nginx && echo RELOADED",
        sudo=True,
    )
    run(
        ngx,
        """
curl -sS -m 10 -o /dev/null -w "http_file:%{http_code}\\n" -H "Host: torbatyar.ir" http://192.168.10.156/78473978.txt
curl -sk -m 10 -o /dev/null -w "https_file:%{http_code}\\n" --resolve torbatyar.ir:443:192.168.10.156 https://torbatyar.ir/78473978.txt
curl -sk -m 15 --resolve torbatyar.ir:443:192.168.10.156 https://torbatyar.ir/ | tr -d '\\r' | grep -E 'enamad|78473978|<title' | head -n 15
""",
    )
    ngx.close()


if __name__ == "__main__":
    main()
