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

APP_HOST, APP_USER, APP_PASS = "192.168.10.162", "morteza", "Moli@5404"


def main():
    c = paramiko.SSHClient()
    c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    c.connect(APP_HOST, username=APP_USER, password=APP_PASS, timeout=30, allow_agent=False, look_for_keys=False)
    cmd = r"""
set -e
cd /home/morteza/torbatyar
# install new deps into the named node_modules volume
docker compose exec -T frontend npm install
docker compose restart frontend
sleep 8
docker compose logs --tail=30 frontend
echo ---
curl -sI http://127.0.0.1:3000/accounting | head -n 15
curl -s http://127.0.0.1:3000/accounting | head -c 400
echo
curl -s https://accounting.torbatyar.ir/health || curl -sk https://accounting.torbatyar.ir/health
echo
"""
    b64 = base64.b64encode(cmd.encode()).decode()
    full = f"echo {APP_PASS!r} | sudo -S -p '' bash -c 'echo {b64} | base64 -d | bash'"
    print("installing frontend deps...")
    _, out, err = c.exec_command(full, timeout=900, get_pty=True)
    text = (out.read() + err.read()).decode("utf-8", "replace")
    print(text[-8000:].encode("ascii", "replace").decode("ascii"))
    print("EXIT", out.channel.recv_exit_status())
    c.close()


if __name__ == "__main__":
    main()
