Files
hermes-recovery/scripts/generate-script-contents.py
T

81 lines
2.4 KiB
Python

#!/usr/bin/env python3
"""
generate-script-contents.py — Generate script-contents.json from known cron job scripts.
Reads the ops-status.json to find all referenced scripts, reads their content
from the filesystem, and writes script-contents.json to the ops data directory.
"""
import json
import os
import subprocess
import sys
from pathlib import Path
OUTPUT_PATH = Path("/var/www/ops/data/script-contents.json")
STATUS_PATH = Path("/var/www/ops/data/ops-status.json")
SCRIPT_DIRS = [
Path("/root/.hermes/scripts"),
Path("/root/.hermes/cron"),
Path("/root"),
]
def find_script(name: str) -> Path | None:
"""Find a script file by name in known script directories."""
if not name:
return None
for d in SCRIPT_DIRS:
p = d / name
if p.exists() and p.is_file():
return p
# Try without leading path components
basename = Path(name).name
for d in SCRIPT_DIRS:
p = d / basename
if p.exists() and p.is_file():
return p
return None
def read_script_content(path: Path) -> str | None:
"""Read a script file, returning first 5000 chars or None."""
try:
content = path.read_text(encoding="utf-8", errors="replace")
if len(content) > 5000:
content = content[:5000] + "\n\n# ... (truncated, full file is larger)"
return content
except Exception:
return None
def main():
if not STATUS_PATH.exists():
print(f"Status file not found: {STATUS_PATH}", file=sys.stderr)
return
try:
data = json.loads(STATUS_PATH.read_text())
except (json.JSONDecodeError, OSError) as e:
print(f"Failed to read status: {e}", file=sys.stderr)
return
cron_jobs = data.get("cron_jobs", [])
result = {}
for job in cron_jobs:
script_name = job.get("script", "")
if not script_name:
continue
script_path = find_script(script_name)
if script_path:
content = read_script_content(script_path)
if content:
result[script_name] = {
"full_path": str(script_path),
"content": content,
}
OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
OUTPUT_PATH.write_text(json.dumps(result, indent=2))
print(f"Wrote {len(result)} script contents to {OUTPUT_PATH}")
if __name__ == "__main__":
main()