#!/usr/bin/env python3
"""Manage the bearer tokens of one endpoint.

Usage:
  getbible-tokens FILE list
  getbible-tokens FILE add --label LABEL [--expires YYYY-MM-DD]
  getbible-tokens FILE revoke ID
  getbible-tokens FILE render-map DOMAIN
  getbible-tokens FILE render-validity-map DOMAIN
  getbible-tokens FILE count

The store is a root-only JSON file. Tokens are 32 random bytes rendered as
lowercase base32, so nginx's case-insensitive map matching loses nothing.
The plaintext stays in the file because nginx must compare exact strings;
`add` prints the new token once on stdout as JSON.
"""

from __future__ import annotations

import base64
import json
import os
import re
import secrets
import sys
import tempfile
from datetime import datetime, timedelta, timezone

UTC = timezone.utc

SCHEMA = "getbible-tokens-v1"


def now() -> str:
    return datetime.now(UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z")


def load(path: str, endpoint: str = "") -> dict:
    if not os.path.exists(path):
        return {"schema": SCHEMA, "endpoint": endpoint, "tokens": []}
    with open(path, encoding="utf-8") as handle:
        data = json.load(handle)
    if data.get("schema") != SCHEMA or not isinstance(data.get("tokens"), list):
        raise SystemExit(f"{path}: not a getbible token store")
    return data


def save(path: str, data: dict) -> None:
    directory = os.path.dirname(path) or "."
    fd, tmp = tempfile.mkstemp(prefix=".tokens.", suffix=".json", dir=directory)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            json.dump(data, handle, indent=2, sort_keys=True)
            handle.write("\n")
        os.chmod(tmp, 0o600)
        os.replace(tmp, path)
    finally:
        if os.path.exists(tmp):
            os.unlink(tmp)


def new_token() -> str:
    raw = base64.b32encode(secrets.token_bytes(32)).decode("ascii").rstrip("=").lower()
    return "gb" + raw


def active(token: dict) -> bool:
    if token.get("revoked_at"):
        return False
    expires = token.get("expires_at")
    if expires and datetime.strptime(expires, "%Y-%m-%d").date() < datetime.fromisoformat(now().replace("Z", "+00:00")).date():
        return False
    return True


def epoch_before(boundary: int) -> str:
    """PCRE for nonnegative integer seconds strictly before a UTC boundary.

    nginx maps cannot compare numeric variables. A decimal range expressed as
    a regex permits expiry checks against $msec on each request, even in old
    workers draining after a reload, without an expiry timer or auth service.
    """
    if boundary <= 0:
        return r"(?!)"
    maximum = str(boundary - 1)
    alternatives = ["0"]
    if len(maximum) > 1:
        alternatives.append(f"[1-9][0-9]{{0,{len(maximum) - 2}}}")
    for index, digit in enumerate(maximum):
        low = 1 if index == 0 else 0
        high = int(digit) - 1
        if high >= low:
            alternatives.append(maximum[:index] + f"[{low}-{high}]" + f"[0-9]{{{len(maximum) - index - 1}}}")
    alternatives.append(maximum)
    return "(?:" + "|".join(alternatives) + ")"


def validated_tokens(data: dict, domain: str):
    if not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?(?:[.][a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)+", domain):
        raise SystemExit("invalid endpoint domain")
    seen = set()
    for token in data["tokens"]:
        if not re.fullmatch(r"tk_[0-9a-f]{8}", token.get("id", "")):
            raise SystemExit("invalid token id in store")
        secret = token.get("token", "")
        if not re.fullmatch(r"gb[a-z2-7]{52}", secret) or secret in seen:
            raise SystemExit("invalid or duplicate bearer token in store")
        seen.add(secret)
        if token.get("expires_at"):
            datetime.strptime(token["expires_at"], "%Y-%m-%d")
        yield token


def cmd_list(data: dict) -> int:
    rows = data["tokens"]
    if not rows:
        print("no tokens")
        return 0
    print(f"{'id':<14} {'state':<8} {'created':<11} {'expires':<11} label")
    for token in rows:
        state = "active" if active(token) else ("revoked" if token.get("revoked_at") else "expired")
        print(
            f"{token['id']:<14} {state:<8} {token['created_at'][:10]:<11} "
            f"{(token.get('expires_at') or '-'):<11} {token.get('label', '')}"
        )
    return 0


def cmd_add(path: str, data: dict, args: list[str]) -> int:
    label = ""
    expires = None
    while args:
        item = args.pop(0)
        if item == "--label":
            label = args.pop(0)
        elif item == "--expires":
            expires = args.pop(0)
            expires = datetime.strptime(expires, "%Y-%m-%d").date().isoformat()
        else:
            raise SystemExit(f"unknown option {item}")
    if not label:
        raise SystemExit("--label is required")
    token = {
        "id": "tk_" + secrets.token_hex(4),
        "label": label,
        "token": new_token(),
        "created_at": now(),
        "expires_at": expires,
        "revoked_at": None,
    }
    data["tokens"].append(token)
    save(path, data)
    print(json.dumps(token))
    return 0


def cmd_revoke(path: str, data: dict, token_id: str) -> int:
    for token in data["tokens"]:
        if token["id"] == token_id:
            if token.get("revoked_at"):
                print(f"{token_id} was already revoked")
                return 0
            token["revoked_at"] = now()
            save(path, data)
            print(f"revoked {token_id}")
            return 0
    raise SystemExit(f"no token with id {token_id}")


def cmd_render_map(data: dict, domain: str) -> int:
    for token in validated_tokens(data, domain):
        if active(token):
            print(f'"{domain} Bearer {token["token"]}" "{token["id"]}";')
    return 0


def cmd_render_validity_map(data: dict, domain: str) -> int:
    for token in validated_tokens(data, domain):
        if not active(token):
            continue
        seconds = "[0-9]+"
        if token.get("expires_at"):
            # A YYYY-MM-DD expiry includes that whole date in UTC.
            end = datetime.strptime(token["expires_at"], "%Y-%m-%d").replace(tzinfo=UTC) + timedelta(days=1)
            seconds = epoch_before(int(end.timestamp()))
        host = domain.replace(".", "[.]")
        print(f'"~^{host} {token["id"]} {seconds}[.][0-9]+$" "{token["id"]}";')
    return 0


def main(argv: list[str]) -> int:
    if len(argv) < 3 or argv[1] in {"-h", "--help"}:
        sys.stderr.write(__doc__)
        return 2
    path, command, rest = argv[1], argv[2], argv[3:]
    data = load(path)
    if command == "list":
        return cmd_list(data)
    if command == "add":
        return cmd_add(path, data, rest)
    if command == "revoke":
        return cmd_revoke(path, data, rest[0])
    if command == "render-map":
        return cmd_render_map(data, rest[0])
    if command == "render-validity-map":
        return cmd_render_validity_map(data, rest[0])
    if command == "count":
        print(sum(1 for token in data["tokens"] if active(token)))
        return 0
    raise SystemExit(f"unknown command {command}")


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