#!/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"


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(c, cmd, sudo=False, timeout=120):
    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 = cmd
    _, o, e = c.exec_command(full, timeout=timeout, get_pty=True)
    print((o.read() + e.read()).decode("utf-8", "replace")[-3000:])


app = connect("192.168.10.162", "morteza")
sftp = app.open_sftp()
sftp.put(str(ROOT / "frontend/app/layout.tsx"), "/home/morteza/torbatyar/frontend/app/layout.tsx")
sftp.close()
run(
    app,
    "rm -f /home/morteza/torbatyar/frontend/public/78473978.txt; "
    "cd /home/morteza/torbatyar && docker compose restart frontend; sleep 6; "
    "curl -sS -m 15 http://127.0.0.1:3000/ | tr '\\n' ' ' | grep -oE '<title>[^<]+</title>|name=\"enamad\"[^>]*>' || echo 'no-enamad-ok'",
    sudo=True,
)
app.close()

ngx = connect("192.168.10.156", "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 -sk -m 15 --resolve torbatyar.ir:443:192.168.10.156 https://torbatyar.ir/ | tr '\\n' ' ' | grep -oE '<title>[^<]+</title>|name=\"enamad\"[^>]*>' || echo 'clean-ok'; "
    "curl -sk -m 8 -o /dev/null -w file=%{http_code} --resolve torbatyar.ir:443:192.168.10.156 https://torbatyar.ir/78473978.txt; echo",
)
ngx.close()
