From bf4e8506550e8a0b871a481f05ce504914d4c0c9 Mon Sep 17 00:00:00 2001 From: Chris Cowan Date: Wed, 22 Oct 2025 09:58:24 -0700 Subject: [PATCH] redid some code --- web/cgi-bin/backupbot.cgi | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/web/cgi-bin/backupbot.cgi b/web/cgi-bin/backupbot.cgi index 707eaa0..fe7356a 100644 --- a/web/cgi-bin/backupbot.cgi +++ b/web/cgi-bin/backupbot.cgi @@ -3,30 +3,32 @@ import cgi import cgitb import os import json +from pathlib import Path cgitb.enable() -print("Content-Type: application/json\n") -ENV_FILE = "/config/backupbot.env" +ENV_FILE = Path("/config/backupbot.env") +print("Content-Type: application/json\n") def read_env(): env = {} - if os.path.exists(ENV_FILE): - with open(ENV_FILE) as f: + if ENV_FILE.exists(): + with ENV_FILE.open() as f: for line in f: line = line.strip() if not line or line.startswith("#") or "=" not in line: continue key, val = line.split("=", 1) - key = key.strip() - val = val.strip().split("#")[0].strip() # strip inline comments - env[key] = val + env[key.strip()] = val.strip().split("#")[0].strip() return env def write_env(env): - with open(ENV_FILE, "w") as f: + # Rotate the old env file just in case + if ENV_FILE.exists(): + ENV_FILE.replace(ENV_FILE.with_suffix(".env.bak")) + with ENV_FILE.open("w") as f: for key, val in env.items(): f.write(f"{key}={val}\n") @@ -34,17 +36,15 @@ def write_env(env): form = cgi.FieldStorage() action = form.getvalue("action") -if action == "get": - env = read_env() - print(json.dumps(env)) -elif action == "set": - try: - raw = os.environ.get("CONTENT_LENGTH") - length = int(raw) if raw else 0 +try: + if action == "get": + print(json.dumps(read_env())) + elif action == "set": + length = int(os.environ.get("CONTENT_LENGTH", "0")) data = json.loads(os.read(0, length)) write_env(data) print(json.dumps({"status": "ok", "message": "Configuration saved."})) - except Exception as e: - print(json.dumps({"status": "error", "message": str(e)})) -else: - print(json.dumps({"status": "error", "message": "Invalid action"})) + else: + print(json.dumps({"status": "error", "message": "Invalid action"})) +except Exception as e: + print(json.dumps({"status": "error", "message": str(e)}))