import pathlib
import pexpect
import shlex


password = pathlib.Path("/home/aaron/.secrets/beget-sftp-password.txt").read_text().strip()
remote = (
    "set -e; "
    "wp_root=/home/m/max9581h/max9581h.beget.tech/public_html; "
    "theme=$(php8.2 /usr/local/bin/wp-cli.phar --path=$wp_root option get stylesheet 2>/dev/null | tr -d '\\r\\n '); "
    "theme_dir=$wp_root/wp-content/themes/$theme; "
    "printf 'THEME=%s\\n' \"$theme\"; "
    "find \"$theme_dir\" -maxdepth 5 -type f "
    "-exec grep -IlE 'Можно с детьми|Дальние туры|Рыбалка|дайвинг|Острова и пляжи' {} + "
    "| head -40; "
    "printf 'MATCHES\\n'; "
    "grep -RInE --binary-files=without-match 'Можно с детьми|Дальние туры|Рыбалка|дайвинг|Острова и пляжи' \"$theme_dir\" "
    "| head -160"
)
command = (
    "ssh -o StrictHostKeyChecking=accept-new "
    "max9581h_aaronseo@max9581h.beget.tech "
    + shlex.quote(remote)
)
child = pexpect.spawn("/bin/bash", ["-lc", command], encoding="utf-8", timeout=120)
match = child.expect(["[Pp]assword:", pexpect.EOF, pexpect.TIMEOUT])
if match == 0:
    child.sendline(password)
    child.expect(pexpect.EOF)
print(child.before)
