import json, re, ssl, sys, urllib.request
from concurrent.futures import ThreadPoolExecutor

CTX = ssl._create_unverified_context()
BASE = 'https://10.112.205.15'
MAXI = int(sys.argv[1]) if len(sys.argv) > 1 else 300
REPO = sys.argv[2] if len(sys.argv) > 2 else 'docker-hosted-dev'
PAT = re.compile(r'(?i)(pass|secret|key|token|credential|jdbc|postgres|mysql|mongo|ldap|smtp|aws|vault)')
ACC = ', '.join([
    'application/vnd.docker.distribution.manifest.v2+json',
    'application/vnd.oci.image.manifest.v1+json',
    'application/vnd.docker.distribution.manifest.list.v2+json',
    'application/vnd.oci.image.index.v1+json',
])


def get(u, accept=None):
    h = {'User-Agent': 'Mozilla/5.0'}
    if accept:
        h['Accept'] = accept
    req = urllib.request.Request(u, headers=h)
    return urllib.request.urlopen(req, timeout=30, context=CTX).read()


def main():
    tok = None
    items = []
    while len(items) < 600:
        u = BASE + '/service/rest/v1/search?repository=%s' % REPO
        if tok:
            u += '&continuationToken=' + tok
        try:
            d = json.loads(get(u))
        except Exception as e:
            print('ERR list', type(e).__name__, str(e)[:60], flush=True)
            break
        items += d.get('items', [])
        tok = d.get('continuationToken')
        if not tok:
            break
    print('images', len(items), flush=True)
    f = open('/tmp/.dk_hits.txt', 'w')
    seen = set()
    cnt = 0
    for it in items:
        if cnt >= MAXI:
            break
        name = it.get('name')
        ver = it.get('version')
        if not name or not ver or (name, ver) in seen:
            continue
        seen.add((name, ver))
        cnt += 1
        try:
            man = json.loads(get(BASE + '/v2/%s/manifests/%s' % (name, ver), ACC))
        except Exception:
            continue
        dig = (man.get('config') or {}).get('digest')
        if not dig:
            continue
        try:
            cfg = json.loads(get(BASE + '/v2/%s/blobs/%s' % (name, dig)))
        except Exception:
            continue
        env = (cfg.get('config') or {}).get('Env') or []
        for e in env:
            if PAT.search(e):
                f.write('%s:%s :: %s\n' % (name, ver, e[:300]))
        if cnt % 50 == 0:
            f.flush()
            print('done', cnt, flush=True)
    f.close()
    print('finished', cnt, flush=True)

main()
