#!/usr/bin/env python3 """Create local Compose settings without overwriting settings or credentials.""" import argparse import os from pathlib import Path from urllib.parse import urlparse from zoneinfo import ZoneInfo, ZoneInfoNotFoundError def host_timezone(): candidates = [os.environ.get("TZ", "")] link = str(Path("/etc/localtime").resolve()) if "/zoneinfo/" in link: candidates.append(link.split("/zoneinfo/", 1)[1]) path = Path("/etc/timezone") if path.exists(): candidates.append(path.read_text().strip()) for candidate in candidates: if not candidate: continue try: ZoneInfo(candidate) return candidate except (ZoneInfoNotFoundError, ValueError): continue raise ValueError("Cannot detect the host timezone; provide --timezone explicitly") def configure(directory, ntfy_url, bind_address, timezone=None, port=8081): directory = Path(directory) url = urlparse(ntfy_url) if (url.scheme not in ("http", "https") or not url.hostname or url.username or url.password or url.query or url.fragment or url.path not in ("", "/")): raise ValueError("--ntfy-url must be an HTTP(S) base URL without credentials or a topic") timezone = timezone or host_timezone() ZoneInfo(timezone) for value in (ntfy_url, bind_address, timezone): if any(char in value for char in "\r\n\x00$#'\" "): raise ValueError("Unsafe configuration value") if not 1 <= port <= 65535: raise ValueError("Invalid pipeline port") settings = directory / ".env" if settings.exists(): raise ValueError(".env exists; edit it rather than overwrite existing settings") secrets = directory / "secrets" secrets.mkdir(mode=0o700, exist_ok=True) token = secrets / "ntfy-token.txt" # Empty until ntfy has issued a token. Never replace an existing credential. try: fd = os.open(token, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) os.close(fd) except FileExistsError: pass with settings.open("x") as file: file.write(f"TZ={timezone}\nNTFY_BASE_URL={ntfy_url.rstrip('/')}\n" f"NTFY_BIND_ADDRESS={bind_address}\nPIPELINES_PORT={port}\n") return timezone if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--ntfy-url", required=True) parser.add_argument("--bind-address", default="127.0.0.1") parser.add_argument("--timezone") parser.add_argument("--port", type=int, default=8081) args = parser.parse_args() try: zone = configure(Path(__file__).resolve().parents[1], args.ntfy_url, args.bind_address, args.timezone, args.port) except (ValueError, ZoneInfoNotFoundError) as error: parser.error(str(error)) print(f"Created .env with timezone {zone}. Configure the ntfy token before starting pipelines.")