import os, socket, time, json, glob, sys

UP = "/var/imunify360/aibolit/resident/in/upload-jobs"
OUT = "/var/imunify360/aibolit/resident/out"
SOCK = "/var/run/defence360agent/aibolit-resident.sock"

# test target file
tf = "/home/john/public_html/test.php"
print("test.php exists:", os.path.exists(tf), "size", os.path.getsize(tf) if os.path.exists(tf) else "-")

# candidate job file
job = {"files": [tf], "dest_paths": []}
jobbytes = json.dumps(job).encode()
print("job bytes:", jobbytes)

# clean any prior test job
for f in glob.glob(UP + "/999999.upload_job*"):
    try: os.unlink(f)
    except Exception as e: print("unlink", f, e)

# drop the job file
jf = UP + "/999999.upload_job"
with open(jf, "wb") as fh:
    fh.write(jobbytes)
os.chmod(jf, 0o644)
print("dropped", jf, os.path.getsize(jf))

# wake the resident via datagram
try:
    s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    s.sendto(b"wake", SOCK)
    s.close()
    print("datagram sent")
except Exception as e:
    print("datagram error:", e)

# wait and poll
for i in range(12):
    time.sleep(1)
    entries = sorted(glob.glob(UP + "/*"))
    out = []
    try:
        out = sorted(os.listdir(OUT))
    except Exception as e:
        out = ["<out err: %s>" % e]
    print("t=%d upload-jobs=%s out=%s" % (i+1, [os.path.basename(x) for x in entries], out))
    if not any(x.endswith("999999.upload_job") for x in entries):
        print("job file consumed/renamed!")
        break
