#!/usr/bin/env python3
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"
S=requests.Session(); S.verify=False; S.trust_env=False
S.headers.update({"User-Agent":"Mozilla/5.0 Chrome/131.0","Accept":"text/html"})
if os.path.exists(CK):
    try:
        for k,v in json.load(open(CK)).items(): S.cookies.set(k,v)
    except Exception: pass
def tok(html):
    m=re.search(r'name="_token" value="([^"]+)"', html) or re.search(r'csrf-token" content="([^"]+)"', html)
    return m.group(1) if m else None
email=sys.argv[1]; name=sys.argv[2]; pw=sys.argv[3]
base=sys.argv[4] if len(sys.argv)>4 else HOST+"/index.php"
r=S.get(base+"/register",timeout=40); print("GET",r.status_code,"len",len(r.content))
t=tok(r.text); print("token",t)
data={"type":"o","name":name,"no_email":"","email":email,"s_designation":"Programmer","s_department":"1","department_id":"1","designation_id":"47","designation_holding_date":"2020-01-01","password":pw,"password_confirmation":pw,"_token":t}
r2=S.post(base+"/register",data=data,timeout=40,allow_redirects=False)
print("POST",r2.status_code,"len",len(r2.content),"loc",r2.headers.get("location","-")[:100])
json.dump({c.name:c.value for c in S.cookies}, open(CK,"w"))
open(os.path.join(BIN,"reg2_resp.html"),"w").write(r2.text)
if r2.status_code in (302,301):
    print("REDIRECT_OK")
# extract messages
seen=set()
for pat in [r'class="[^"]*(?:invalid-feedback|alert|error)[^"]*"[^>]*>(.*?)</(?:span|div|li|p)>', r'<strong>(.*?)</strong>', r'<li>(.*?)</li>']:
    for e in re.findall(pat, r2.text, re.S)[:12]:
        e=re.sub(r'<[^>]+>','',e); e=re.sub(r'\s+',' ',e).strip()
        if e and e not in seen and len(e)<250: seen.add(e); print("MSG:",e)

