#!/bin/sh
# SPDX-License-Identifier: LicenseRef-CMSD-1.0
# Copyright (c) 2026 CyberMind — Gérald Kerma <devel@cybermind.fr>
# Source-Disclosed License — All rights reserved except as expressly granted.
# See LICENCE-CMSD-1.0.md for terms.
#
# Task 5 (tor-enhancement-phase1): boot-time Tor hidden-service persist
# reconcile. Re-applies the torrc HiddenService* stanza for every `active`
# emancipated service (see api/main.py: tor_reconcile_persist) whose HS dir
# is currently absent — idempotent, never re-creates an existing HS dir, so
# .onion addresses survive reboots unchanged. Runs as root (torrc + systemctl
# reload tor need privilege), invoked by
# secubox-exposure-tor-reconcile.service on boot.
set -e
/usr/bin/python3 -c "import sys; sys.path.insert(0, '/usr/lib/secubox/exposure'); import api.main as m; m.tor_reconcile_persist()"

# Discovery perms: tor creates each HS leaf dir 0700 and hostname 0600, so the
# secubox-tor API (running with SupplementaryGroups=debian-tor) can't read the
# .onion to list it. The .onion address is PUBLIC info (unlike private_key, left
# untouched at 0600), so make the leaf dirs group-traversable and the hostname
# group-readable for the debian-tor group. Best-effort, root-only, idempotent.
# tor forces /var/lib/tor to 0700 on every start, so the secubox-user modules
# (aggregator/tor/exposure) can't read HS hostnames directly regardless of group.
# As root, publish a secubox-readable cache of the (public) .onion addresses that
# the secubox-tor discovery/webui reads. private_key is never touched/exported.
CACHE_DIR=/var/lib/secubox/tor
mkdir -p "$CACHE_DIR"
/usr/bin/python3 - <<'PY' 2>/dev/null || true
import json, glob, os
out = []
seen = set()
for hf in sorted(glob.glob('/var/lib/tor/hidden_services/*/hostname') +
                 glob.glob('/var/lib/tor/*/hostname')):
    try:
        name = os.path.basename(os.path.dirname(hf)).replace('hidden_service_', '')
        if name in seen:
            continue
        onion = open(hf).read().strip()
        if onion.endswith('.onion'):
            out.append({"name": name, "onion": onion}); seen.add(name)
    except Exception:
        pass
os.makedirs('/var/lib/secubox/tor', exist_ok=True)
with open('/var/lib/secubox/tor/onions.json', 'w') as f:
    json.dump({"services": out}, f)
PY
chmod 0755 "$CACHE_DIR" 2>/dev/null || true
chmod 0644 "$CACHE_DIR/onions.json" 2>/dev/null || true
