import sys, time, os, json, urllib.request, ssl
# Read TXT value from file (written by lego's challenge output)
valfile = "/work/exploit/certcheck/acme_txt_value.txt"
domain = "exnessvpn74efaadb.duckdns.org"
token_file = "/work/exploit/certcheck/duck_token.txt"

ctx = ssl.create_default_context(); ctx.check_hostname=False; ctx.verify_mode=ssl.CERT_NONE
opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=ctx))

def get_token():
    if os.path.exists(token_file):
        return open(token_file).read().strip()
    return None

print("=== DNS SOLVER START ===", flush=True)
# Wait for lego to write the txt value
for i in range(60):
    if os.path.exists(valfile) and os.path.getsize(valfile)>0:
        break
    time.sleep(2)
if not os.path.exists(valfile) or os.path.getsize(valfile)==0:
    print("NO TXT VALUE FILE", flush=True); sys.exit(1)
txtval = open(valfile).read().strip()
print("TXT value:", txtval[:80], flush=True)

# Try to set via duckdns if we have a token
tok = get_token()
if tok:
    url = f"https://www.duckdns.org/update?domains={domain.split('.')[0]}&token={tok}&txt={txtval}&verbose=true"
    try:
        r = opener.open(url, timeout=15)
        print("DuckDNS update:", r.read().decode(), flush=True)
    except Exception as e:
        print("duck err", e, flush=True)
else:
    print("No token - waiting for manual set", flush=True)

# Wait for propagation then signal done
time.sleep(30)
open("/work/exploit/certcheck/acme_done.flag","w").write("done")
print("SOLVER DONE", flush=True)
