#!/usr/bin/env python3
import socket,sys,base64,re,binascii
HOST=sys.argv[1] if len(sys.argv)>1 else '10.0.0.25'
PORT=int(sys.argv[2]) if len(sys.argv)>2 else 6379
ARGV=sys.argv[3:]
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):
    l=f.readline()
    if not l: raise EOFError
    t=l[:1]; d=l[1:].rstrip(b'\r\n')
    if t==b'+': return d
    if t==b'-': return {'err':d.decode('utf-8','replace')}
    if t==b':': return int(d)
    if t==b'$':
        n=int(d)
        if n<0: return None
        x=f.read(n); f.read(2); return x
    if t==b'*':
        n=int(d)
        if n<0: return None
        return [read(f) for _ in range(n)]
    return d
def fmtreply(r):
    if isinstance(r,dict): return 'ERR '+r.get('err','')
    if isinstance(r,bytes):
        ss=[x.decode('utf-8','replace') for x in re.findall(rb'[\x20-\x7e\xc2-\xf4][\x20-\x7e\x80-\xbf]*',r) if len(x)>=3]
        uuids=re.findall(rb'[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}',r)
        return 'LEN %d\nUUID %s\nASCII %s\nB64 %s'%(len(r),' '.join(x.decode() for x in uuids),repr(ss[:120]),base64.b64encode(r).decode())
    if isinstance(r,list):
        return 'ARRAY %d %s'%(len(r),repr([x.decode('utf-8','replace') if isinstance(x,bytes) else x for x in r[:50]]))
    return repr(r)
s=socket.create_connection((HOST,PORT),8); f=s.makefile('rb')
def cmd(*a):
    s.sendall(enc(*a)); return read(f)
try:
    if not ARGV:
        for c in [('PING',),('INFO','server'),('CONFIG','GET','dir'),('CONFIG','GET','dbfilename'),('CONFIG','GET','logfile'),('CONFIG','GET','requirepass'),('ACL','WHOAMI'),('MODULE','LIST'),('DBSIZE',)]:
            print('CMD',c,'=>',fmtreply(cmd(*c)),flush=True)
    elif ARGV[0]=='HGET' and len(ARGV)>=3:
        print('HGET',ARGV[1],ARGV[2]); print(fmtreply(cmd('HGET',ARGV[1],ARGV[2])))
    elif ARGV[0]=='HKEYS' and len(ARGV)>=2:
        print(fmtreply(cmd('HKEYS',ARGV[1])))
    elif ARGV[0]=='GET' and len(ARGV)>=2:
        print(fmtreply(cmd('GET',ARGV[1])))
    elif ARGV[0]=='RAW':
        print(fmtreply(cmd(*ARGV[1:])))
    else:
        print(fmtreply(cmd(*ARGV)))
finally:
    try: s.close()
    except: pass
