import json, subprocess, sys

def curl(args, cj):
    return subprocess.run(["curl","-sk","-m","15"]+args+["-H","Host: www.itportal.cc","-c",cj,"-b",cj], capture_output=True, text=True)

def login(user, pwd):
    cj = "/tmp/cj_login.txt"
    subprocess.run(["rm","-f",cj])
    # GET establish flow
    curl([f"https://112.199.81.2:37443/api/v3/flows/executor/default-authentication-flow/","-o","/dev/null"], cj)
    # POST uid_field
    curl([f"https://112.199.81.2:37443/api/v3/flows/executor/default-authentication-flow/","-X","POST","-H","Content-Type: application/json","-d",json.dumps({"component":"ak-stage-identification","uid_field":user}),"-o","/dev/null"], cj)
    # GET next stage (password)
    r = curl([f"https://112.199.81.2:37443/api/v3/flows/executor/default-authentication-flow/","-o","/tmp/stage.json"], cj)
    stage = json.load(open("/tmp/stage.json"))
    comp = stage.get("component")
    if comp != "ak-stage-password":
        return f"stage={comp} err={stage.get('error_message')}"
    # POST password
    curl([f"https://112.199.81.2:37443/api/v3/flows/executor/default-authentication-flow/","-X","POST","-H","Content-Type: application/json","-d",json.dumps({"component":"ak-stage-password","password":pwd}),"-o","/tmp/resp.json"], cj)
    resp = json.load(open("/tmp/resp.json"))
    return f"resp_component={resp.get('component')} err={json.dumps(resp.get('response_errors') or resp.get('error_message'))}"

if __name__ == "__main__":
    u = sys.argv[1]; p = sys.argv[2]
    print(login(u,p))
