#!/usr/bin/env python3
"""persisted-secret <file> — print the secret kept in <file>, minting and saving one first.

The Lite entrypoint calls this for NEXTAUTH_SECRET when the operator gives none: the first boot
mints a random 64-hex-character secret and saves it (0600, in a 0700 directory), and every later
boot of the same container prints the saved one, so sign-in cookies and emailed links survive a
restart. A file holding fewer than 32 bytes is replaced. When the file cannot be written the
minted value is still printed, for this boot only, and a warning goes to stderr. Never prints
anything but the secret to stdout.
"""
import os
import secrets
import sys

MIN_BYTES = 32


def main(argv):
    if len(argv) != 2:
        print("usage: persisted-secret <file>", file=sys.stderr)
        return 2
    path = argv[1]
    try:
        with open(path, encoding="utf-8") as f:
            kept = f.read().strip()
        if len(kept.encode("utf-8")) >= MIN_BYTES:
            print(kept)
            return 0
    except FileNotFoundError:
        pass
    except OSError as e:
        print(f"persisted-secret: cannot read {path}: {e}", file=sys.stderr)
    value = secrets.token_hex(32)
    try:
        os.makedirs(os.path.dirname(path) or ".", mode=0o700, exist_ok=True)
        tmp = f"{path}.tmp"
        fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            f.write(value + "\n")
        os.replace(tmp, path)
    except OSError as e:
        print(f"persisted-secret: cannot save {path} ({e}); this value lasts until the container "
              f"restarts", file=sys.stderr)
    print(value)
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))
