"""Try R2 create via curl + Global API Key from staged env (no secret echo).""" from __future__ import annotations import json import os import subprocess import sys from pathlib import Path STAGED = Path(__file__).resolve().parents[1] / ".refresh" / "cf_creds.env" ACCT = "510534f7f6284344aadaf2f5a0794d48" BUCKET = "climperor-player-data" def load() -> tuple[str, str]: email = os.environ.get("CLOUDFLARE_EMAIL") key = os.environ.get("CLOUDFLARE_API_KEY") if STAGED.is_file(): for line in STAGED.read_text(encoding="utf-8").splitlines(): if "=" not in line: continue k, v = line.split("=", 1) if k.strip() == "CLOUDFLARE_EMAIL": email = v.strip() elif k.strip() == "CLOUDFLARE_API_KEY": key = v.strip() if not email or not key: raise SystemExit("missing credentials") return email, key def curl_json(method: str, url: str, email: str, key: str, body: dict | None = None) -> tuple[int, str]: cmd = [ "curl.exe", "-sS", "-w", "\nHTTP_CODE:%{http_code}", "--max-time", "60", "-X", method, url, "-H", f"X-Auth-Email: {email}", "-H", f"X-Auth-Key: {key}", "-H", "Content-Type: application/json", ] if body is not None: cmd.extend(["-d", json.dumps(body)]) proc = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace") out = proc.stdout or "" code = 0 if "HTTP_CODE:" in out: body_text, _, code_s = out.rpartition("HTTP_CODE:") try: code = int(code_s.strip()) except ValueError: code = 0 out = body_text.strip() else: out = (proc.stderr or out)[:300] return code, out[:400] def main() -> int: email, key = load() base = f"https://api.cloudflare.com/client/v4/accounts/{ACCT}/r2/buckets" code, body = curl_json("GET", f"{base}/{BUCKET}", email, key) print(f"GET bucket -> {code} {body[:160]!r}") if code == 200: print("r2 already exists") return 0 code, body = curl_json("POST", base, email, key, {"name": BUCKET}) print(f"POST bucket -> {code} {body[:200]!r}") return 0 if code in (200, 201) or "already exists" in body.lower() else 1 if __name__ == "__main__": raise SystemExit(main())