#!/usr/bin/env python3 """Explicit local/service launcher. --check validates config, not live integrations.""" import argparse import json import os from pathlib import Path import runpy import sys ROOT = Path(__file__).resolve().parents[1] COMPONENTS = { "bot": "bot/grok_bot.py", "miniapp": "bot/webapp/server.py", "gateway": "gateway/grok-web-skin.py", } CONFIG_KEYS = ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG") PATH_GROUPS = ( (("IISHKO_BOT_DB", "GROK_BOT_DB", "GATE_BOT_DB"), "bot_db", "/opt/grok-bot/bot.db"), (("IISHKO_GW_DB", "GATE_NEWAPI_DB"), "newapi_db", "/opt/grok-gateway/new-api/one-api.db"), (("IISHKO_SKIN_DB", "GATE_TG_DB"), None, "/opt/grok-web-skin-tg.db"), ) def _pick(keys, process, file_values, default): # A service/environment alias beats a canonical value in the optional file. for layer in (process, file_values): for key in keys: if layer.get(key): return layer[key] return default def _path(root, value): path = Path(value).expanduser() return str((root / path).resolve()) def prepare_environment(root=ROOT, env_file=None, process=None): root = Path(root).resolve() process = dict(os.environ if process is None else process) explicit = env_file is not None path = Path(env_file).expanduser() if explicit else root / ".env" if not path.is_absolute(): path = root / path file_values = {} if path.exists(): from dotenv import dotenv_values # No shell evaluation, parent-file discovery or secret interpolation. file_values = {key: value for key, value in dotenv_values( path, encoding="utf-8-sig", interpolate=False).items() if value is not None} elif explicit: raise ValueError("explicit environment file does not exist") env = {**file_values, **process} config_path = _path(root, _pick(CONFIG_KEYS, process, file_values, "bot/config.json")) for key in CONFIG_KEYS: env[key] = config_path config = {} try: with open(config_path, encoding="utf-8-sig") as source: loaded = json.load(source) if isinstance(loaded, dict): config = loaded except (OSError, ValueError): pass # check_configuration reports the config error without exposing values. for keys, config_key, default in PATH_GROUPS: fallback = config.get(config_key) or default value = _path(root, _pick(keys, process, file_values, fallback)) for key in keys: env[key] = value env["IISHKO_APP_ROOT"] = _path(root, _pick(("IISHKO_APP_ROOT",), process, file_values, "bot")) for name in ("TG_SID_SECRET_FILE", "IISHKO_BOT_SOURCE", "IISHKO_PROVIDERS_FILE", "IISHKO_ECON_STATE"): if env.get(name): env[name] = _path(root, env[name]) upstream = _pick(("IISHKO_UPSTREAM", "NEWAPI_URL"), process, file_values, config.get("newapi_url")) if upstream: env["IISHKO_UPSTREAM"] = env["NEWAPI_URL"] = upstream module_dirs = [env["IISHKO_APP_ROOT"], str(root / "gateway"), str(root / "bot/webapp")] env["IISHKO_RUNTIME_PATHS"] = os.pathsep.join(module_dirs) # Do not inherit a POSIX-only PYTHONPATH from the distributed .env template. env["PYTHONPATH"] = os.pathsep.join(module_dirs) return env def check_configuration(env): problems = [] try: with open(env["GROK_BOT_CFG"], encoding="utf-8-sig") as source: config = json.load(source) except (OSError, ValueError): return ["bot config is missing, unreadable or invalid JSON (GROK_BOT_CFG)"] if not isinstance(config, dict): return ["bot config must be a JSON object"] for key, name in (("bot_token", "GROK_BOT_TOKEN"), ("newapi_pass", "NEWAPI_PASS")): if env.get(name): config[key] = env[name] for key in ("bot_token", "main_key", "channel_username", "newapi_pass"): value = config.get(key) if not isinstance(value, str) or not value.strip() or "REPLACE_ME" in value or "your_" in value: problems.append("bot config requires a real value for " + key) if not Path(env["IISHKO_APP_ROOT"]).is_dir(): problems.append("IISHKO_APP_ROOT must be an existing bot module directory") if not Path(env["IISHKO_GW_DB"]).is_file(): problems.append("IISHKO_GW_DB must point to your existing New API SQLite database") for key in ("IISHKO_BOT_DB", "IISHKO_SKIN_DB"): path = Path(env[key]) if (path.exists() and not path.is_file()) or not path.parent.is_dir(): problems.append(key + " must name a file in an existing data directory") return problems def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("component", choices=COMPONENTS) parser.add_argument("--env-file", help="explicit dotenv file; real environment takes priority") parser.add_argument("--check", action="store_true", help="offline config preflight, not an app smoke test") args = parser.parse_args(argv) try: env = prepare_environment(env_file=args.env_file) problems = check_configuration(env) except (OSError, ValueError, ImportError): problems = ["environment setup failed; check the env file and installed requirements"] if problems: for problem in problems: print("ERROR: " + problem, file=sys.stderr) return 2 if args.check: print("Configuration preflight passed; no app started or integrations checked.") return 0 os.environ.update(env) os.chdir(ROOT) target = ROOT / COMPONENTS[args.component] sys.path[:0] = [str(target.parent), *env["IISHKO_RUNTIME_PATHS"].split(os.pathsep)] sys.argv = [str(target)] runpy.run_path(str(target), run_name="__main__") return 0 if __name__ == "__main__": raise SystemExit(main())