File size: 2,527 Bytes
6bff6a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from __future__ import annotations

import os
import tomllib
from pathlib import Path
from typing import Any


def parse_bool(raw: str) -> bool:
    return raw.strip().lower() in {"1", "true", "yes", "on"}


def quote_string(value: str) -> str:
    escaped = value.replace("\\", "\\\\").replace('"', '\\"')
    return f'"{escaped}"'


def format_toml_value(value: Any) -> str:
    if isinstance(value, bool):
        return "true" if value else "false"
    if isinstance(value, (int, float)):
        return str(value)
    if isinstance(value, list):
        return "[" + ",".join(format_toml_value(item) for item in value) + "]"
    return quote_string(str(value))


def load_existing_config(path: Path) -> dict[str, Any]:
    if not path.exists():
        return {}
    with path.open("rb") as handle:
        return tomllib.load(handle)


def update_section(target: dict[str, Any], section: str, key: str, env_name: str, *, as_bool: bool = False) -> None:
    raw = os.getenv(env_name)
    if raw is None:
        return
    sec = target.setdefault(section, {})
    sec[key] = parse_bool(raw) if as_bool else raw


def write_config(path: Path, config: dict[str, Any]) -> None:
    lines: list[str] = []
    for section, items in config.items():
        if not isinstance(items, dict):
            continue
        lines.append(f"[{section}]")
        for key, value in items.items():
            lines.append(f"{key} = {format_toml_value(value)}")
        lines.append("")
    path.write_text("\n".join(lines).strip() + "\n", encoding="utf-8")


def main() -> None:
    data_dir = Path(os.getenv("DATA_DIR", "/app/data"))
    config_path = data_dir / "config.toml"
    data_dir.mkdir(parents=True, exist_ok=True)

    config = load_existing_config(config_path)

    update_section(config, "app", "api_key", "GROK2API_API_KEYS")
    update_section(config, "app", "app_key", "GROK2API_APP_KEY")
    update_section(config, "app", "function_key", "GROK2API_FUNCTION_KEY")
    update_section(config, "app", "function_enabled", "GROK2API_FUNCTION_ENABLED", as_bool=True)
    update_section(config, "app", "app_url", "GROK2API_APP_URL")

    update_section(config, "proxy", "base_proxy_url", "GROK2API_PROXY_BASE_URL")
    update_section(config, "proxy", "asset_proxy_url", "GROK2API_PROXY_ASSET_URL")
    update_section(config, "proxy", "cf_clearance", "GROK2API_CF_CLEARANCE")
    update_section(config, "proxy", "cf_cookies", "GROK2API_CF_COOKIES")

    write_config(config_path, config)


if __name__ == "__main__":
    main()