import json, subprocess, sys, os, time

BASE = "https://112.199.81.2:37443/api/v3/flows/executor/default-authentication-flow/"
HOST = "www.itportal.cc"

def curl(cj, args, out="/dev/null", headers=None):
    cmd = ["curl","-sk","-m","15", "-H", f"Host: {HOST}"]
    if headers:
        for h in headers:
            cmd += ["-H", h]
    if cj:
        cmd += ["-c", cj, "-b", cj]
    cmd += args
    r = subprocess.run(cmd, capture_output=True, text=True)
    return r

def full_flow(user, pwd, verbose=False):
    cj = "/tmp/cj_probe_%d.txt" % os.getpid()
    if os.path.exists(cj): os.remove(cj)
    # step1 GET establish flow
    r1 = curl(cj, [BASE, "-o", "/dev/null", "-w", "%{http_code}"])
    # step2 POST uid_field
    r2 = curl(cj, [BASE, "-X","POST","-H","Content-Type: application/json","-d", json.dumps({"component":"ak-stage-identification","uid_field":user}), "-o","/dev/null","-w","%{http_code}"])
    # step3 GET password stage
    r3 = curl(cj, [BASE, "-o", "/tmp/stage_probe.json", "-w", "%{http_code}"])
    stage = json.load(open("/tmp/stage_probe.json"))
    comp = stage.get("component")
    if comp != "ak-stage-password":
        return {"stage": comp, "err": stage.get("error_message"), "r1":r1.stdout, "r2":r2.stdout, "r3":r3.stdout}
    # step4 POST password
    r4 = curl(cj, [BASE, "-X","POST","-H","Content-Type: application/json","-d", json.dumps({"component":"ak-stage-password","password":pwd}), "-o","/tmp/resp_probe.json","-w","%{http_code}", "-D","/tmp/hdr_probe.txt"])
    try:
        resp = json.load(open("/tmp/resp_probe.json"))
    except:
        resp = {}
    hdrs = open("/tmp/hdr_probe.txt").read()
    loc = [l for l in hdrs.splitlines() if l.lower().startswith("location:")]
    return {"r1":r1.stdout,"r2":r2.stdout,"r3":r3.stdout,"r4":r4.stdout,
            "resp_component": resp.get("component"),
            "response_errors": resp.get("response_errors"),
            "error_message": resp.get("error_message"),
            "to": resp.get("to"),
            "location": loc,
            "resp_keys": list(resp.keys())}

if __name__ == "__main__":
    u = sys.argv[1] if len(sys.argv)>1 else "admin"
    p = sys.argv[2] if len(sys.argv)>2 else "wrongpass123"
    r = full_flow(u, p)
    print(json.dumps(r, indent=2, default=str))
