#!/usr/bin/env python3
# persistent-cookie HTTP helper run ON relay host
import sys, os, json, re
import requests
requests.packages.urllib3.disable_warnings()
BIN=os.path.dirname(os.path.abspath(__file__))
CK=os.path.join(BIN,"ck.json")
HOST="https://eee.ruet.ac.bd"
def load():
    S=requests.Session(); S.verify=False; S.trust_env=False
    S.headers.update({"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0.0.0 Safari/537.36"})
    if os.path.exists(CK):
        try:
            for k,v in json.load(open(CK)).items(): S.cookies.set(k,v)
        except Exception: pass
    return S
def save(S):
    try: json.dump({c.name:c.value for c in S.cookies}, open(CK,"w"))
    except Exception: pass
def main():
    global HOST
    args=sys.argv[1:]
    method=args[0].upper(); path=args[1]
    data=None; headers={}; outfile=None; limit=6000; raw=None
    i=2
    while i<len(args):
        a=args[i]
        if a=="-d":
            if data is None: data={}
            k,_,v=args[i+1].partition("="); data[k]=v; i+=2
        elif a=="-H":
            k,_,v=args[i+1].partition(": "); headers[k]=v; i+=2
        elif a=="-o": outfile=args[i+1]; i+=2
        elif a=="-l": limit=int(args[i+1]); i+=2
        elif a=="--host": HOST=args[i+1]; i+=2
        elif a=="--rawfile": raw=open(args[i+1],'rb').read(); i+=2
        else: i+=1
    S=load(); url=HOST+path
    try:
        if method=="GET": r=S.get(url,headers=headers,timeout=45,allow_redirects=False)
        elif method=="POST": r=S.post(url,data=data,headers=headers,timeout=45,allow_redirects=False)
        elif method=="POSTJ": r=S.post(url,json=data,headers=headers,timeout=45,allow_redirects=False)
        elif method=="PUT": r=S.put(url,data=data or raw,headers=headers,timeout=45,allow_redirects=False)
        else: r=S.request(method,url,data=data,headers=headers,timeout=45,allow_redirects=False)
    except Exception as e:
        print("ERR",type(e).__name__,str(e)[:200]); return
    save(S)
    body=r.content
    if outfile:
        try: open(outfile,'wb').write(body)
        except Exception: pass
    print("STATUS",r.status_code,"LEN",len(body))
    for h in ("location","content-type","set-cookie"):
        if h in r.headers:
            v=r.headers[h]
            if h=="set-cookie": v=v[:120]
            print("H",h,"=",v)
    txt=body.decode('utf-8','replace')
    sys.stdout.write(txt[:limit])
if __name__=="__main__": main()

