diff --git a/stage_dashboard_bridge/README.md b/stage_dashboard_bridge/README.md new file mode 100644 index 0000000..4127463 --- /dev/null +++ b/stage_dashboard_bridge/README.md @@ -0,0 +1,26 @@ +# Dashboard Bridge + +Local HTTP-to-MQTT bridge for dashboards running on Edge. + +## Endpoints +- `POST /api/event` +- `GET /api/component?id=` +- `GET /api/health` + +## Runtime +- bind: `127.0.0.1` +- port: `8787` +- MQTT broker: `127.0.0.1:1883` +- systemd unit: `iomatex-dashboard-bridge.service` + +## Install +```bash +sudo bash stage_dashboard_bridge/dashboard_bridge_installer.sh +``` + +## Quick check +```bash +curl http://127.0.0.1:8787/api/health +curl -X POST http://127.0.0.1:8787/api/event -H 'Content-Type: application/json' -d '{"id":5744,"value":"start","title":"Switch_On"}' +curl 'http://127.0.0.1:8787/api/component?id=5744' +``` diff --git a/stage_dashboard_bridge/dashboard_bridge_core/backend/bridge.py b/stage_dashboard_bridge/dashboard_bridge_core/backend/bridge.py new file mode 100644 index 0000000..098c518 --- /dev/null +++ b/stage_dashboard_bridge/dashboard_bridge_core/backend/bridge.py @@ -0,0 +1,381 @@ +#!/usr/bin/env python3 +import json +import os +import queue +import re +import sys +import threading +import time +from datetime import datetime, timezone +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlparse +from urllib.parse import urlparse as parse_url + +try: + import paho.mqtt.client as mqtt +except Exception: + mqtt = None + + +DEFAULT_BIND = "127.0.0.1" +DEFAULT_PORT = 8787 +DEFAULT_MQTT_URL = "mqtt://127.0.0.1:1883" +DEFAULT_SERVICE_NAME = "dashboard-bridge" +DEVICE_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") + + +def log(message): + print(f"[dashboard-bridge] {message}", file=sys.stderr, flush=True) + + +def utc_timestamp(): + return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S+00") + + +def device_id_from_hostname(): + host = "" + try: + host = os.uname().nodename + except Exception: + host = "" + host = (host or "").strip().split(".", 1)[0] + if host and DEVICE_ID_RE.fullmatch(host): + return host + return "unknown-edge" + + +def parse_mqtt_url(raw_url): + parsed = parse_url(str(raw_url or "").strip() or DEFAULT_MQTT_URL) + if parsed.scheme not in ("mqtt", "tcp"): + raise RuntimeError(f"Unsupported MQTT URL: {raw_url}") + return parsed.hostname or "127.0.0.1", parsed.port or 1883 + + +def mqtt_err_success(): + return getattr(mqtt, "MQTT_ERR_SUCCESS", 0) if mqtt is not None else 0 + + +class BridgeState: + def __init__(self): + self.lock = threading.Lock() + self.components = {} + self.raw_payload = None + self.last_message_at = "" + self.mqtt_connected = False + self.mqtt_last_error = "" + + def set_mqtt_connected(self, value): + with self.lock: + self.mqtt_connected = bool(value) + if value: + self.mqtt_last_error = "" + + def set_mqtt_error(self, message): + with self.lock: + self.mqtt_connected = False + self.mqtt_last_error = str(message or "") + + def update_components(self, payload): + components = payload.get("components") if isinstance(payload, dict) else None + if not isinstance(components, dict): + raise ValueError("MQTT payload does not contain object field 'components'") + normalized = {} + for key, value in components.items(): + if not isinstance(value, dict): + continue + normalized[str(key)] = value + with self.lock: + self.components = normalized + self.raw_payload = payload + self.last_message_at = utc_timestamp() + + def get_component(self, component_id): + with self.lock: + component = self.components.get(str(component_id)) + return dict(component) if isinstance(component, dict) else None + + def health_snapshot(self): + with self.lock: + return { + "mqtt_connected": self.mqtt_connected, + "mqtt_last_error": self.mqtt_last_error, + "last_message_at": self.last_message_at, + } + + +class MqttBridge: + def __init__(self, mqtt_url, device_id, state): + self.mqtt_url = mqtt_url + self.device_id = device_id + self.state = state + self.host, self.port = parse_mqtt_url(mqtt_url) + self.state_topic = f"it-screen/dev/client/pub/component/plays/{device_id}" + self._publish_lock = threading.Lock() + self._ready = threading.Event() + self._client = None + + if mqtt is None: + log("paho-mqtt is unavailable; MQTT features disabled") + self.state.set_mqtt_error("paho-mqtt not installed") + return + + client_id = f"dashboard-bridge-{device_id}-{int(time.time() * 1000)}" + self._client = mqtt.Client(client_id=client_id, clean_session=True) + self._client.on_connect = self._on_connect + self._client.on_disconnect = self._on_disconnect + self._client.on_message = self._on_message + self._client.on_connect_fail = self._on_connect_fail + + def start(self): + if self._client is None: + return + log(f"starting MQTT client url={self.mqtt_url} state_topic={self.state_topic}") + try: + self._client.connect_async(self.host, self.port, keepalive=30) + self._client.loop_start() + except Exception as exc: + self.state.set_mqtt_error(str(exc)) + log(f"mqtt start failed: {exc}") + + def stop(self): + if self._client is None: + return + try: + self._client.loop_stop() + except Exception: + pass + try: + self._client.disconnect() + except Exception: + pass + + def is_connected(self): + return self._ready.is_set() + + def publish_event(self, component_id, value, title): + if self._client is None: + raise RuntimeError("MQTT client is unavailable") + topic = f"it-screen/dev/client/sub/event/push/{component_id}" + payload = { + "action": "push", + "value": str(value), + "id": int(component_id), + "time": utc_timestamp(), + "user": "root", + "title": str(title), + } + serialized = json.dumps(payload, ensure_ascii=True, separators=(",", ":")) + with self._publish_lock: + if not self.is_connected(): + raise RuntimeError("MQTT is not connected") + result = self._client.publish(topic, serialized, qos=0, retain=False) + deadline = time.time() + 2.0 + while time.time() < deadline: + if result.is_published(): + log(f"published topic={topic} payload={serialized}") + return topic, payload + time.sleep(0.05) + raise RuntimeError("MQTT publish timeout") + + def _on_connect(self, client, userdata, flags, rc): + if rc != 0: + self._ready.clear() + self.state.set_mqtt_error(f"connect failed ({rc})") + log(f"mqtt connect failed rc={rc}") + return + result, _ = client.subscribe(self.state_topic, qos=0) + if result != mqtt_err_success(): + self._ready.clear() + self.state.set_mqtt_error("subscribe failed") + log(f"mqtt subscribe failed topic={self.state_topic} rc={result}") + return + self._ready.set() + self.state.set_mqtt_connected(True) + log(f"mqtt connected host={self.host} port={self.port} subscribed={self.state_topic}") + + def _on_disconnect(self, client, userdata, rc): + self._ready.clear() + if rc in (0, None): + self.state.set_mqtt_error("") + log("mqtt disconnected cleanly") + return + self.state.set_mqtt_error(f"disconnect ({rc})") + log(f"mqtt disconnected rc={rc}") + + def _on_connect_fail(self, client, userdata): + self._ready.clear() + self.state.set_mqtt_error("connect failed") + log("mqtt connect failed") + + def _on_message(self, client, userdata, msg): + raw = msg.payload.decode("utf-8", errors="ignore") + try: + payload = json.loads(raw) + except Exception as exc: + log(f"ignored invalid mqtt json topic={msg.topic} error={exc}") + return + try: + self.state.update_components(payload) + except Exception as exc: + log(f"ignored invalid mqtt payload topic={msg.topic} error={exc}") + return + log(f"state updated topic={msg.topic}") + + +class Handler(BaseHTTPRequestHandler): + server_version = "IOMATEXDashboardBridge/0.1" + + def log_message(self, format_, *args): + log("%s - %s" % (self.address_string(), format_ % args)) + + @property + def app(self): + return self.server.app + + def end_headers(self): + self.send_header("Cache-Control", "no-store") + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("Access-Control-Allow-Headers", "Content-Type") + self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + super().end_headers() + + def send_json(self, payload, code=200): + body = json.dumps(payload, ensure_ascii=False).encode("utf-8") + self.send_response(code) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def read_json_body(self): + content_length = self.headers.get("Content-Length", "").strip() + try: + length = int(content_length or "0") + except ValueError: + return None, "Invalid Content-Length" + try: + raw = self.rfile.read(length) if length > 0 else b"" + except Exception as exc: + return None, f"Failed to read request body: {exc}" + if not raw: + return None, "Request body is required" + try: + payload = json.loads(raw.decode("utf-8", errors="strict")) + except Exception: + return None, "Invalid JSON body" + if not isinstance(payload, dict): + return None, "JSON body must be an object" + return payload, "" + + def do_OPTIONS(self): + self.send_response(204) + self.send_header("Content-Length", "0") + self.end_headers() + + def do_GET(self): + parsed = urlparse(self.path) + if parsed.path == "/api/health": + snapshot = self.app.state.health_snapshot() + self.send_json({ + "ok": True, + "service": self.app.service_name, + "device_id": self.app.device_id, + "mqtt": bool(snapshot["mqtt_connected"]), + }) + return + if parsed.path == "/api/component": + params = parse_qs(parsed.query) + component_id = str((params.get("id") or [""])[0]).strip() + if not component_id: + log("bad request: component id is required") + self.send_json({"ok": False, "error": "id is required"}, code=400) + return + component = self.app.state.get_component(component_id) + if component is None: + self.send_json({"ok": False, "error": "Component not found"}, code=404) + return + self.send_json({ + "ok": True, + "device_id": self.app.device_id, + "component": component, + }) + return + self.send_json({"ok": False, "error": "Not found"}, code=404) + + def do_POST(self): + parsed = urlparse(self.path) + if parsed.path != "/api/event": + self.send_json({"ok": False, "error": "Not found"}, code=404) + return + + payload, error = self.read_json_body() + if payload is None: + log(f"bad request: {error}") + self.send_json({"ok": False, "error": error}, code=400) + return + + component_id = payload.get("id") + value = str(payload.get("value", "")).strip() + title = str(payload.get("title", "")).strip() + try: + component_id = int(component_id) + except Exception: + log("bad request: id must be an integer") + self.send_json({"ok": False, "error": "id must be an integer"}, code=400) + return + if component_id <= 0: + log("bad request: id must be a positive integer") + self.send_json({"ok": False, "error": "id must be a positive integer"}, code=400) + return + if not value: + log("bad request: value is required") + self.send_json({"ok": False, "error": "value is required"}, code=400) + return + if not title: + title = f"Component_{component_id}" + + try: + topic, mqtt_payload = self.app.mqtt_bridge.publish_event(component_id, value, title) + except Exception as exc: + log(f"publish failed component_id={component_id} error={exc}") + self.send_json({"ok": False, "error": str(exc)}, code=503) + return + + self.send_json({ + "ok": True, + "published": True, + "topic": topic, + "payload": mqtt_payload, + }) + + +class App: + def __init__(self): + self.bind = os.environ.get("DASHBOARD_BRIDGE_BIND", DEFAULT_BIND).strip() or DEFAULT_BIND + self.port = int(os.environ.get("DASHBOARD_BRIDGE_PORT", str(DEFAULT_PORT)).strip() or str(DEFAULT_PORT)) + self.service_name = os.environ.get("DASHBOARD_BRIDGE_SERVICE_NAME", DEFAULT_SERVICE_NAME).strip() or DEFAULT_SERVICE_NAME + self.mqtt_url = os.environ.get("DASHBOARD_BRIDGE_MQTT_URL", DEFAULT_MQTT_URL).strip() or DEFAULT_MQTT_URL + self.device_id = os.environ.get("DASHBOARD_BRIDGE_DEVICE_ID", "").strip() or device_id_from_hostname() + self.state = BridgeState() + self.mqtt_bridge = MqttBridge(self.mqtt_url, self.device_id, self.state) + self.httpd = ThreadingHTTPServer((self.bind, self.port), Handler) + self.httpd.app = self + + def run(self): + log( + f"starting http bind={self.bind} port={self.port} device_id={self.device_id} mqtt_url={self.mqtt_url}" + ) + self.mqtt_bridge.start() + try: + self.httpd.serve_forever() + finally: + self.mqtt_bridge.stop() + + +def main(): + app = App() + app.run() + + +if __name__ == "__main__": + main() diff --git a/stage_dashboard_bridge/dashboard_bridge_installer.sh b/stage_dashboard_bridge/dashboard_bridge_installer.sh new file mode 100644 index 0000000..11b5490 --- /dev/null +++ b/stage_dashboard_bridge/dashboard_bridge_installer.sh @@ -0,0 +1,195 @@ +#!/usr/bin/env bash +set -euo pipefail + +if head -c 3 "$0" 2>/dev/null | grep -q $'^\xEF\xBB\xBF'; then + echo "ERROR: UTF-8 BOM detected. Save as UTF-8 (without BOM)." >&2 + exit 1 +fi +if grep -q $'\r' "$0" 2>/dev/null; then + echo "ERROR: CRLF detected. Convert file to UNIX (LF) EOL." >&2 + exit 1 +fi + +need_root() { + [ "$(id -u)" -eq 0 ] || { + echo "Run as root: sudo bash $0" >&2 + exit 1 + } +} +need_root + +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +export DEBIAN_FRONTEND=noninteractive + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +SRC_ROOT="${SCRIPT_DIR}/dashboard_bridge_core" +APP_DIR="/opt/iomatex-dashboard-bridge" +BACKEND_DIR="${APP_DIR}/backend" +SERVICE_NAME="iomatex-dashboard-bridge.service" +CFG_PATH="/etc/iomatex/dashboard_bridge.env" +APP_BIND="${DASHBOARD_BRIDGE_BIND:-127.0.0.1}" +APP_PORT="${DASHBOARD_BRIDGE_PORT:-8787}" +MQTT_URL="${DASHBOARD_BRIDGE_MQTT_URL:-mqtt://127.0.0.1:1883}" +ts="$(date +%s)" +PREV_DIR="${APP_DIR}.prev.${ts}" +STAGE_DIR="${APP_DIR}.staging.${ts}" +STAGE_BACKEND_DIR="${STAGE_DIR}/backend" + +copy_tree() { + local src="$1" + local dst="$2" + mkdir -p "$dst" + cp -a "${src}/." "$dst/" +} + +require_file() { + local path="$1" + [ -f "$path" ] || { + echo "ERROR: required file is missing: $path" >&2 + exit 1 + } +} + +systemctl_try() { + systemctl "$@" >/dev/null 2>&1 || true +} + +rollback_deploy() { + systemctl_try stop "${SERVICE_NAME}" + rm -rf "${APP_DIR}" + if [ -d "${PREV_DIR}" ]; then + mv "${PREV_DIR}" "${APP_DIR}" + systemctl daemon-reload >/dev/null 2>&1 || true + systemctl_try start "${SERVICE_NAME}" + fi +} + +wait_for_local_http() { + local attempt max_attempts url code + max_attempts=30 + url="http://${APP_BIND}:${APP_PORT}/api/health" + echo "Smoke-check: waiting for ${url}" + for attempt in $(seq 1 "${max_attempts}"); do + if ! systemctl is-active --quiet "${SERVICE_NAME}"; then + echo "Smoke-check attempt ${attempt}/${max_attempts}: ${SERVICE_NAME} is not active yet" + sleep 1 + continue + fi + if ! ss -ltnp 2>/dev/null | grep -q "${APP_BIND}:${APP_PORT}"; then + echo "Smoke-check attempt ${attempt}/${max_attempts}: nothing is listening on ${APP_BIND}:${APP_PORT} yet" + sleep 1 + continue + fi + code="$(curl -sS -o /tmp/iomatex-dashboard-bridge-health.$$ -w '%{http_code}' --max-time 5 "${url}" 2>/tmp/iomatex-dashboard-bridge-health.err || true)" + echo "Smoke-check attempt ${attempt}/${max_attempts}: GET ${url} -> ${code:-curl_failed}" + if [ "${code}" = "200" ] && grep -q '"service": "dashboard-bridge"' "/tmp/iomatex-dashboard-bridge-health.$$"; then + rm -f "/tmp/iomatex-dashboard-bridge-health.$$" "/tmp/iomatex-dashboard-bridge-health.err" + return 0 + fi + sleep 1 + done + echo "Smoke-check failed for ${url}" >&2 + if [ -f "/tmp/iomatex-dashboard-bridge-health.err" ] && [ -s "/tmp/iomatex-dashboard-bridge-health.err" ]; then + cat "/tmp/iomatex-dashboard-bridge-health.err" >&2 || true + fi + rm -f "/tmp/iomatex-dashboard-bridge-health.$$" "/tmp/iomatex-dashboard-bridge-health.err" + return 1 +} + +step_n=0 +TOTAL_STEPS=8 + +step() { + local label="$1" + local filled empty bar percent + step_n=$((step_n + 1)) + percent=$(( step_n * 100 / TOTAL_STEPS )) + filled=$(( step_n * 20 / TOTAL_STEPS )) + empty=$(( 20 - filled )) + bar="$(printf '%*s' "$filled" '' | tr ' ' '#')$(printf '%*s' "$empty" '' | tr ' ' '-')" + echo + echo "[${bar}] ${step_n}/${TOTAL_STEPS} (${percent}%)" + echo "=== Step ${step_n}: ${label} ===" +} + +step "Validate source tree" +require_file "${SRC_ROOT}/backend/bridge.py" + +step "Ensure runtime packages exist" +apt-get update +apt-get install -y python3 python3-paho-mqtt curl +python3 --version + +step "Prepare directories" +mkdir -p /etc/iomatex +rm -rf "${STAGE_DIR}" +mkdir -p "${STAGE_BACKEND_DIR}" + +step "Install bridge runtime files" +copy_tree "${SRC_ROOT}/backend" "${STAGE_BACKEND_DIR}" +require_file "${STAGE_BACKEND_DIR}/bridge.py" + +step "Write config and systemd unit" +cat > "${CFG_PATH}" < "/etc/systemd/system/${SERVICE_NAME}" <<'UNIT' +[Unit] +Description=IOMATEX Dashboard Bridge +After=network-online.target mosquitto.service +Wants=network-online.target mosquitto.service + +[Service] +Type=simple +Environment="DASHBOARD_BRIDGE_BIND=127.0.0.1" +Environment="DASHBOARD_BRIDGE_PORT=8787" +Environment="DASHBOARD_BRIDGE_MQTT_URL=mqtt://127.0.0.1:1883" +EnvironmentFile=-/etc/iomatex/dashboard_bridge.env +WorkingDirectory=/opt/iomatex-dashboard-bridge +ExecStart=/usr/bin/python3 /opt/iomatex-dashboard-bridge/backend/bridge.py +Restart=always +RestartSec=2 +User=root +Group=root + +[Install] +WantedBy=multi-user.target +UNIT + +step "Validate runtime" +python3 -m py_compile "${STAGE_BACKEND_DIR}/bridge.py" + +step "Activate bridge service" +if [ -d "${APP_DIR}" ]; then + rm -rf "${PREV_DIR}" + mv "${APP_DIR}" "${PREV_DIR}" +fi +mv "${STAGE_DIR}" "${APP_DIR}" +systemctl daemon-reload +systemctl_try stop "${SERVICE_NAME}" +systemctl_try reset-failed "${SERVICE_NAME}" +if ! systemctl enable --now "${SERVICE_NAME}"; then + echo "ERROR: failed to start ${SERVICE_NAME}; rolling back deploy" >&2 + rollback_deploy + exit 1 +fi + +step "Smoke-check" +if ! wait_for_local_http; then + echo "ERROR: bridge did not become reachable on ${APP_BIND}:${APP_PORT}; rolling back deploy" >&2 + systemctl status "${SERVICE_NAME}" --no-pager -n 40 || true + rollback_deploy + exit 1 +fi + +step "Summary" +echo "Bridge health: curl http://${APP_BIND}:${APP_PORT}/api/health" +echo "Bridge event: curl -X POST http://${APP_BIND}:${APP_PORT}/api/event -H 'Content-Type: application/json' -d '{\"id\":5744,\"value\":\"start\",\"title\":\"Switch_On\"}'" +echo "Bridge component: curl 'http://${APP_BIND}:${APP_PORT}/api/component?id=5744'" +echo "Service: systemctl status ${SERVICE_NAME} --no-pager -n 40" +echo "Logs: journalctl -u ${SERVICE_NAME} --no-pager -n 80" +echo "Install dir: ${APP_DIR}" +echo "Config: ${CFG_PATH}" diff --git a/stage_dashboards/README.md b/stage_dashboards/README.md new file mode 100644 index 0000000..882f092 --- /dev/null +++ b/stage_dashboards/README.md @@ -0,0 +1,35 @@ +# Edge Dashboards + +This stage deploys standalone dashboards on dedicated ports without touching the existing admin UI. + +## Model +- `dashboard_id = port` +- current runtime source directory: `/var/lib/itscreen/Downloads/it-screen/` +- deployed runtime lives in `/opt/iomatex-dashboards/` +- one systemd instance serves one dashboard: `iomatex-dashboard@.service` +- current HTML selection mode: newest `.html` file by modification time +- dashboard server proxies bridge API: + - `/api/bridge/event` -> `http://127.0.0.1:8787/api/event` + - `/api/bridge/component` -> `http://127.0.0.1:8787/api/component` + - `/api/bridge/health` -> `http://127.0.0.1:8787/api/health` + +## Current behavior for `5678` +- service reads `.html` files from `/var/lib/itscreen/Downloads/it-screen/` +- if at least one `.html` file exists, `/` returns the selected file as the dashboard entrypoint +- if no `.html` file exists, `/` returns fallback page: `No dashboard HTML file found` +- non-HTML static files from the same directory remain directly accessible by path +- HTML for LAN clients should call same-origin bridge routes, for example `/api/bridge/event` + +## Install +```bash +sudo bash stage_dashboards/dashboard_installer.sh +``` + +## Verify +```bash +ls -lah /var/lib/itscreen/Downloads/it-screen/ +curl -I http://127.0.0.1:5678/ +curl http://127.0.0.1:5678/ +systemctl status iomatex-dashboard@5678.service --no-pager -n 40 +journalctl -u iomatex-dashboard@5678.service --no-pager -n 50 +``` diff --git a/stage_dashboards/dashboard_core/backend/dashboard_locator.py b/stage_dashboards/dashboard_core/backend/dashboard_locator.py new file mode 100644 index 0000000..1a36cb1 --- /dev/null +++ b/stage_dashboards/dashboard_core/backend/dashboard_locator.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +from pathlib import Path + + +DEFAULT_SELECTION_MODE = "newest" + + +def list_html_candidates(source_dir): + root = Path(source_dir).resolve() + if not root.is_dir(): + return [] + candidates = [] + for path in root.iterdir(): + if not path.is_file(): + continue + if path.suffix.lower() != ".html": + continue + try: + stat = path.stat() + except OSError: + continue + candidates.append( + { + "path": path, + "name": path.name, + "mtime": float(stat.st_mtime), + "size": int(stat.st_size), + } + ) + return candidates + + +def select_dashboard_html(source_dir, selection_mode=DEFAULT_SELECTION_MODE): + candidates = list_html_candidates(source_dir) + if not candidates: + return None + + mode = str(selection_mode or DEFAULT_SELECTION_MODE).strip().lower() + if mode == "alphabetical": + selected = sorted(candidates, key=lambda item: (item["name"].lower(), item["name"]))[0] + else: + selected = sorted( + candidates, + key=lambda item: (-item["mtime"], item["name"].lower(), item["name"]), + )[0] + return selected diff --git a/stage_dashboards/dashboard_core/backend/static_server.py b/stage_dashboards/dashboard_core/backend/static_server.py new file mode 100644 index 0000000..fa8e561 --- /dev/null +++ b/stage_dashboards/dashboard_core/backend/static_server.py @@ -0,0 +1,348 @@ +#!/usr/bin/env python3 +import argparse +import http.client +import functools +import json +import mimetypes +import os +import posixpath +import sys +from html import escape +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import urlencode, urlparse + +from dashboard_locator import DEFAULT_SELECTION_MODE, select_dashboard_html + + +DEFAULT_BIND = "0.0.0.0" +DEFAULT_PORT = 5678 +DEFAULT_APP_DIR = "/opt/iomatex-dashboards" +DEFAULT_SOURCE_DIR = "/var/lib/itscreen/Downloads/it-screen" +DEFAULT_BRIDGE_URL = "http://127.0.0.1:8787" + + +def env_int(name, default): + raw = os.environ.get(name, "").strip() + if not raw: + return default + try: + return int(raw) + except ValueError as exc: + raise SystemExit(f"Invalid integer in {name}: {raw}") from exc + + +def build_parser(): + parser = argparse.ArgumentParser(description="Serve one dashboard from an external HTML source directory") + parser.add_argument("--bind", default=os.environ.get("DASHBOARD_BIND", DEFAULT_BIND)) + parser.add_argument("--port", type=int, default=env_int("DASHBOARD_PORT", DEFAULT_PORT)) + parser.add_argument("--dashboard-id", default=os.environ.get("DASHBOARD_ID", "")) + parser.add_argument("--root", default=os.environ.get("DASHBOARD_ROOT", "")) + parser.add_argument("--source-dir", default=os.environ.get("DASHBOARD_SOURCE_DIR", DEFAULT_SOURCE_DIR)) + parser.add_argument( + "--selection-mode", + default=os.environ.get("DASHBOARD_SELECTION_MODE", DEFAULT_SELECTION_MODE), + ) + parser.add_argument("--bridge-url", default=os.environ.get("DASHBOARD_BRIDGE_URL", DEFAULT_BRIDGE_URL)) + return parser + + +def resolve_dashboard_root(app_dir, dashboard_id, explicit_root): + if explicit_root: + root = Path(explicit_root) + else: + root = Path(app_dir) / "dashboards" / str(dashboard_id) + return root.resolve() + + +class BridgeProxy: + def __init__(self, bridge_url): + parsed = urlparse(str(bridge_url or DEFAULT_BRIDGE_URL).strip() or DEFAULT_BRIDGE_URL) + self.scheme = parsed.scheme or "http" + self.host = parsed.hostname or "127.0.0.1" + self.port = parsed.port or 8787 + self.base_path = (parsed.path or "").rstrip("/") + + def request(self, method, path, query="", body=None, headers=None): + target = f"{self.base_path}{path}" + if query: + target = f"{target}?{query}" + connection_cls = http.client.HTTPSConnection if self.scheme == "https" else http.client.HTTPConnection + conn = connection_cls(self.host, self.port, timeout=5) + try: + conn.request(method, target, body=body, headers=headers or {}) + response = conn.getresponse() + payload = response.read() + return response.status, response.getheaders(), payload + finally: + conn.close() + + +class DashboardHandler(SimpleHTTPRequestHandler): + server_version = "IOMATEXDashboardHTTP/0.2" + + def __init__( + self, + *args, + directory=None, + dashboard_id=None, + source_dir=None, + selection_mode=None, + bridge_proxy=None, + **kwargs, + ): + self.dashboard_id = str(dashboard_id or "").strip() + self.source_dir = Path(source_dir).resolve() if source_dir else None + self.selection_mode = str(selection_mode or DEFAULT_SELECTION_MODE).strip().lower() + self.bridge_proxy = bridge_proxy + super().__init__(*args, directory=directory, **kwargs) + + def select_entrypoint(self): + if not self.source_dir: + return None + selection = select_dashboard_html(self.source_dir, self.selection_mode) + if selection: + print( + f"[dashboard:{self.dashboard_id}] selected html file={selection['path']} mode={self.selection_mode}", + file=sys.stderr, + ) + else: + print( + f"[dashboard:{self.dashboard_id}] no html file found in {self.source_dir}", + file=sys.stderr, + ) + return selection + + def render_fallback_page(self): + source_dir = escape(str(self.source_dir or DEFAULT_SOURCE_DIR)) + dashboard_id = escape(self.dashboard_id or "unknown") + return f""" + + + + + No dashboard HTML file found + + + +
+

No dashboard HTML file found

+

Dashboard id: {dashboard_id}

+

Expected source directory: {source_dir}

+

Add any .html file to that directory and restart the dashboard service.

+
+ + +""" + + def send_fallback_page(self): + payload = self.render_fallback_page().encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + def serve_entrypoint(self): + selection = self.select_entrypoint() + if not selection: + self.send_fallback_page() + return + target = selection["path"] + try: + with target.open("rb") as fh: + payload = fh.read() + except OSError as exc: + self.send_error(500, f"Failed to read dashboard html: {exc}") + return + content_type = f"{self.guess_type(str(target))}; charset=utf-8" + self.send_response(200) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + def translate_path(self, path): + path = path.split("?", 1)[0].split("#", 1)[0] + normalized = posixpath.normpath(path) + parts = [part for part in normalized.split("/") if part and part not in {".", ".."}] + full_path = Path(self.directory) + for part in parts: + full_path = full_path / part + return str(full_path) + + def end_headers(self): + self.send_header("Cache-Control", "no-store") + super().end_headers() + + def guess_type(self, path): + guessed, _ = mimetypes.guess_type(path) + return guessed or "application/octet-stream" + + def log_message(self, format_, *args): + message = "%s - - [%s] %s\n" % ( + self.address_string(), + self.log_date_time_string(), + format_ % args, + ) + sys.stderr.write(message) + + def bridge_request(self, method, path, query="", body=None): + if self.bridge_proxy is None: + self.send_error(502, "Bridge proxy is unavailable") + return + headers = {"Accept": "application/json"} + if body is not None: + headers["Content-Type"] = "application/json; charset=utf-8" + headers["Content-Length"] = str(len(body)) + try: + status, response_headers, payload = self.bridge_proxy.request( + method=method, + path=path, + query=query, + body=body, + headers=headers, + ) + except Exception as exc: + print(f"[dashboard:{self.dashboard_id}] bridge proxy error: {exc}", file=sys.stderr) + self.send_response(502) + error_payload = json.dumps({"ok": False, "error": "Bridge is unavailable"}).encode("utf-8") + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(error_payload))) + self.end_headers() + self.wfile.write(error_payload) + return + + self.send_response(status) + content_type_sent = False + content_length_sent = False + for key, value in response_headers: + lowered = key.lower() + if lowered in {"transfer-encoding", "connection", "server", "date"}: + continue + if lowered == "content-type": + content_type_sent = True + if lowered == "content-length": + content_length_sent = True + self.send_header(key, value) + if not content_type_sent: + self.send_header("Content-Type", "application/json; charset=utf-8") + if not content_length_sent: + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + def route_bridge(self, method): + parsed = urlparse(self.path) + bridge_path = parsed.path.removeprefix("/api/bridge") + if not bridge_path: + bridge_path = "" + bridge_path = f"/api{bridge_path}" + if method == "POST": + content_length = self.headers.get("Content-Length", "").strip() + try: + length = int(content_length or "0") + except ValueError: + self.send_response(400) + payload = json.dumps({"ok": False, "error": "Invalid Content-Length"}).encode("utf-8") + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + return + body = self.rfile.read(length) if length > 0 else b"" + self.bridge_request(method, bridge_path, parsed.query, body=body) + return + self.bridge_request(method, bridge_path, parsed.query) + + def do_OPTIONS(self): + if self.path.split("?", 1)[0].split("#", 1)[0].startswith("/api/bridge"): + self.route_bridge("OPTIONS") + return + self.send_response(204) + self.send_header("Content-Length", "0") + self.end_headers() + + def do_GET(self): + path = self.path.split("?", 1)[0].split("#", 1)[0] + if path.startswith("/api/bridge"): + self.route_bridge("GET") + return + if path in {"/", "/index.html"}: + self.serve_entrypoint() + return + super().do_GET() + + def do_POST(self): + path = self.path.split("?", 1)[0].split("#", 1)[0] + if path.startswith("/api/bridge"): + self.route_bridge("POST") + return + self.send_error(404) + + +def main(): + args = build_parser().parse_args() + app_dir = os.environ.get("DASHBOARD_APP_DIR", DEFAULT_APP_DIR) + dashboard_id = str(args.dashboard_id or args.port).strip() + if not dashboard_id: + raise SystemExit("dashboard id is required") + + root = resolve_dashboard_root(app_dir, dashboard_id, args.root) + source_dir = Path(args.source_dir or DEFAULT_SOURCE_DIR).resolve() + root.mkdir(parents=True, exist_ok=True) + source_dir.mkdir(parents=True, exist_ok=True) + bridge_proxy = BridgeProxy(args.bridge_url) + + handler = functools.partial( + DashboardHandler, + directory=str(source_dir), + dashboard_id=dashboard_id, + source_dir=str(source_dir), + selection_mode=args.selection_mode, + bridge_proxy=bridge_proxy, + ) + server = ThreadingHTTPServer((str(args.bind), int(args.port)), handler) + print( + f"[dashboard:{dashboard_id}] serving source_dir={source_dir} mode={args.selection_mode} bridge_url={args.bridge_url} on http://{args.bind}:{args.port}", + file=sys.stderr, + ) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/stage_dashboards/dashboard_core/dashboards/5678/index.html b/stage_dashboards/dashboard_core/dashboards/5678/index.html new file mode 100644 index 0000000..4fb6472 --- /dev/null +++ b/stage_dashboards/dashboard_core/dashboards/5678/index.html @@ -0,0 +1,373 @@ + + + + + + Edge Start Stop Dashboard + + + +
+
Edge Dashboard
+

Start Stop Control

+

LAN dashboard with same-origin bridge proxy. Button events are published by Edge to local MQTT.

+ +
+
+
+
Component
+
5744
+
+
IDLE
+
+ +
0seconds remaining
+ + +
+
+
Duration
+
0
+
+
+
Rest Duration
+
0
+
+
+ +
Connecting to Edge bridge…
+
+
+ + + + diff --git a/stage_dashboards/dashboard_installer.sh b/stage_dashboards/dashboard_installer.sh new file mode 100644 index 0000000..51c4ec9 --- /dev/null +++ b/stage_dashboards/dashboard_installer.sh @@ -0,0 +1,242 @@ +#!/usr/bin/env bash +set -euo pipefail + +if head -c 3 "$0" 2>/dev/null | grep -q $'^\xEF\xBB\xBF'; then + echo "ERROR: UTF-8 BOM detected. Save as UTF-8 (without BOM)." >&2 + exit 1 +fi +if grep -q $'\r' "$0" 2>/dev/null; then + echo "ERROR: CRLF detected. Convert file to UNIX (LF) EOL." >&2 + exit 1 +fi + +need_root() { + [ "$(id -u)" -eq 0 ] || { + echo "Run as root: sudo bash $0" >&2 + exit 1 + } +} +need_root + +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +export DEBIAN_FRONTEND=noninteractive + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +SRC_ROOT="${SCRIPT_DIR}/dashboard_core" +APP_DIR="/opt/iomatex-dashboards" +BACKEND_DIR="${APP_DIR}/backend" +DASHBOARDS_DIR="${APP_DIR}/dashboards" +SERVICE_TEMPLATE_NAME="iomatex-dashboard@.service" +SERVICE_INSTANCE_PORT="${DASHBOARD_PORT:-5678}" +SERVICE_INSTANCE_NAME="iomatex-dashboard@${SERVICE_INSTANCE_PORT}.service" +CFG_DIR="/etc/iomatex/dashboards.d" +CFG_PATH="${CFG_DIR}/${SERVICE_INSTANCE_PORT}.env" +APP_BIND="${DASHBOARD_BIND:-0.0.0.0}" +SOURCE_DIR="${DASHBOARD_SOURCE_DIR:-/var/lib/itscreen/Downloads/it-screen}" +SELECTION_MODE="${DASHBOARD_SELECTION_MODE:-newest}" +BRIDGE_URL="${DASHBOARD_BRIDGE_URL:-http://127.0.0.1:8787}" +ts="$(date +%s)" +PREV_DIR="${APP_DIR}.prev.${ts}" +STAGE_DIR="${APP_DIR}.staging.${ts}" +STAGE_BACKEND_DIR="${STAGE_DIR}/backend" +STAGE_DASHBOARDS_DIR="${STAGE_DIR}/dashboards" + +detect_edge_ip() { + local route_ip host_ip + route_ip="$(ip route get 1.1.1.1 2>/dev/null | awk '/src/ {for (i = 1; i <= NF; i++) if ($i == "src") {print $(i+1); exit}}' || true)" + if [ -n "${route_ip}" ]; then + printf '%s\n' "${route_ip}" + return 0 + fi + host_ip="$(hostname -I 2>/dev/null | awk '{print $1}' || true)" + if [ -n "${host_ip}" ]; then + printf '%s\n' "${host_ip}" + return 0 + fi + return 1 +} + +copy_tree() { + local src="$1" + local dst="$2" + mkdir -p "$dst" + cp -a "${src}/." "$dst/" +} + +require_file() { + local path="$1" + [ -f "$path" ] || { + echo "ERROR: required file is missing: $path" >&2 + exit 1 + } +} + +systemctl_try() { + systemctl "$@" >/dev/null 2>&1 || true +} + +wait_for_local_http() { + local attempt max_attempts url code probe_host + max_attempts=30 + probe_host="${EDGE_IP:-127.0.0.1}" + url="http://${probe_host}:${SERVICE_INSTANCE_PORT}/" + echo "Smoke-check: waiting for ${url}" + for attempt in $(seq 1 "${max_attempts}"); do + if ! systemctl is-active --quiet "${SERVICE_INSTANCE_NAME}"; then + echo "Smoke-check attempt ${attempt}/${max_attempts}: ${SERVICE_INSTANCE_NAME} is not active yet" + sleep 1 + continue + fi + if ! ss -ltnp 2>/dev/null | grep -q ":${SERVICE_INSTANCE_PORT} "; then + echo "Smoke-check attempt ${attempt}/${max_attempts}: nothing is listening on :${SERVICE_INSTANCE_PORT} yet" + sleep 1 + continue + fi + code="$(curl -sS -o /tmp/iomatex-dashboard-smoke.$$ -w '%{http_code}' --max-time 5 "${url}" 2>/tmp/iomatex-dashboard-smoke.err || true)" + echo "Smoke-check attempt ${attempt}/${max_attempts}: GET ${url} -> ${code:-curl_failed}" + if [ "${code}" = "200" ] && grep -Eq "No dashboard HTML file found|" "/tmp/iomatex-dashboard-smoke.$$"; then + rm -f "/tmp/iomatex-dashboard-smoke.$$" "/tmp/iomatex-dashboard-smoke.err" + return 0 + fi + sleep 1 + done + echo "Smoke-check failed for ${url}" >&2 + if [ -f "/tmp/iomatex-dashboard-smoke.err" ] && [ -s "/tmp/iomatex-dashboard-smoke.err" ]; then + cat "/tmp/iomatex-dashboard-smoke.err" >&2 || true + fi + rm -f "/tmp/iomatex-dashboard-smoke.$$" "/tmp/iomatex-dashboard-smoke.err" + return 1 +} + +rollback_deploy() { + systemctl_try stop "${SERVICE_INSTANCE_NAME}" + rm -rf "${APP_DIR}" + if [ -d "${PREV_DIR}" ]; then + mv "${PREV_DIR}" "${APP_DIR}" + systemctl daemon-reload >/dev/null 2>&1 || true + systemctl_try start "${SERVICE_INSTANCE_NAME}" + fi +} + +step_n=0 +TOTAL_STEPS=8 + +step() { + local label="$1" + local filled empty bar percent + step_n=$((step_n + 1)) + percent=$(( step_n * 100 / TOTAL_STEPS )) + filled=$(( step_n * 20 / TOTAL_STEPS )) + empty=$(( 20 - filled )) + bar="$(printf '%*s' "$filled" '' | tr ' ' '#')$(printf '%*s' "$empty" '' | tr ' ' '-')" + echo + echo "[${bar}] ${step_n}/${TOTAL_STEPS} (${percent}%)" + echo "=== Step ${step_n}: ${label} ===" +} + +step "Validate source tree" +require_file "${SRC_ROOT}/backend/static_server.py" +require_file "${SRC_ROOT}/backend/dashboard_locator.py" +EDGE_IP="$(detect_edge_ip || true)" +if [ -n "${EDGE_IP}" ]; then + echo "Detected EDGE_IP=${EDGE_IP}" +else + EDGE_IP="127.0.0.1" + echo "WARNING: failed to detect Edge IPv4 address, fallback to ${EDGE_IP}" +fi + +step "Ensure runtime packages exist" +apt-get update +apt-get install -y python3 curl +python3 --version + +step "Prepare directories" +mkdir -p "${CFG_DIR}" +rm -rf "${STAGE_DIR}" +mkdir -p "${STAGE_BACKEND_DIR}" "${STAGE_DASHBOARDS_DIR}" + +step "Install dashboard runtime files" +copy_tree "${SRC_ROOT}/backend" "${STAGE_BACKEND_DIR}" +copy_tree "${SRC_ROOT}/dashboards" "${STAGE_DASHBOARDS_DIR}" +require_file "${STAGE_BACKEND_DIR}/static_server.py" +require_file "${STAGE_BACKEND_DIR}/dashboard_locator.py" + +step "Write instance config and systemd template" +cat > "${CFG_PATH}" < "/etc/systemd/system/${SERVICE_TEMPLATE_NAME}" <<'UNIT' +[Unit] +Description=IOMATEX Edge Dashboard %i +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +Environment="DASHBOARD_ID=%i" +Environment="DASHBOARD_PORT=%i" +Environment="DASHBOARD_BIND=0.0.0.0" +Environment="DASHBOARD_APP_DIR=/opt/iomatex-dashboards" +Environment="DASHBOARD_ROOT=/opt/iomatex-dashboards/dashboards/%i" +Environment="DASHBOARD_SOURCE_DIR=/var/lib/itscreen/Downloads/it-screen" +Environment="DASHBOARD_SELECTION_MODE=newest" +Environment="DASHBOARD_BRIDGE_URL=http://127.0.0.1:8787" +EnvironmentFile=-/etc/iomatex/dashboards.d/%i.env +WorkingDirectory=/opt/iomatex-dashboards +ExecStart=/usr/bin/python3 /opt/iomatex-dashboards/backend/static_server.py +Restart=always +RestartSec=2 +User=root +Group=root + +[Install] +WantedBy=multi-user.target +UNIT + +step "Validate runtime" +python3 -m py_compile "${STAGE_BACKEND_DIR}/static_server.py" "${STAGE_BACKEND_DIR}/dashboard_locator.py" + +step "Activate dashboard service" +if [ -d "${APP_DIR}" ]; then + rm -rf "${PREV_DIR}" + mv "${APP_DIR}" "${PREV_DIR}" +fi +mv "${STAGE_DIR}" "${APP_DIR}" +systemctl daemon-reload +systemctl_try stop "${SERVICE_INSTANCE_NAME}" +systemctl_try reset-failed "${SERVICE_INSTANCE_NAME}" +if ! systemctl enable --now "${SERVICE_INSTANCE_NAME}"; then + echo "ERROR: failed to start ${SERVICE_INSTANCE_NAME}; rolling back deploy" >&2 + rollback_deploy + exit 1 +fi + +step "Smoke-check" +if ! wait_for_local_http; then + echo "ERROR: dashboard did not become reachable on port ${SERVICE_INSTANCE_PORT}; rolling back deploy" >&2 + systemctl status "${SERVICE_INSTANCE_NAME}" --no-pager -n 40 || true + rollback_deploy + exit 1 +fi + +step "Summary" +echo "Dashboard URL: http://${EDGE_IP}:${SERVICE_INSTANCE_PORT}" +echo "Network check: curl http://${EDGE_IP}:${SERVICE_INSTANCE_PORT}/" +echo "Fallback local check: curl http://127.0.0.1:${SERVICE_INSTANCE_PORT}/" +echo "Service: systemctl status ${SERVICE_INSTANCE_NAME} --no-pager -n 40" +echo "Install dir: ${APP_DIR}" +echo "Dashboards dir: ${DASHBOARDS_DIR}" +echo "Backend dir: ${BACKEND_DIR}" +echo "Instance config: ${CFG_PATH}" +echo "Dashboard source dir: ${SOURCE_DIR}" +echo "HTML selection mode: ${SELECTION_MODE}" +echo "Bridge proxy url: ${BRIDGE_URL}" +echo "Systemd template: /etc/systemd/system/${SERVICE_TEMPLATE_NAME}" diff --git a/stage_env/rollback_pulse_changes.sh b/stage_env/rollback_pulse_changes.sh deleted file mode 100755 index d1c4aac..0000000 --- a/stage_env/rollback_pulse_changes.sh +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - -LOG="/var/log/iomatex-pulse-rollback.log" -mkdir -p /var/log >/dev/null 2>&1 || true - -log() { - local line="[$(date -u +'%F %T UTC')] $*" - echo "$line" - echo "$line" >>"$LOG" 2>/dev/null || true -} - -require_root() { - if [ "${EUID:-$(id -u)}" -ne 0 ]; then - echo "Run as root: sudo bash $0" >&2 - exit 1 - fi -} - -latest_backup() { - local pattern="$1" - ls -1t $pattern 2>/dev/null | head -n1 || true -} - -backup_current() { - local path="$1" - [ -f "$path" ] || return 0 - cp -a "$path" "${path}.rollback.$(date +%F-%H%M%S)" 2>/dev/null || true -} - -restore_from_backup() { - local target="$1" - local pattern="$2" - local src="" - - src="$(latest_backup "$pattern")" - if [ -n "$src" ]; then - backup_current "$target" - cp -a "$src" "$target" - log "Restored $target from backup: $src" - return 0 - fi - - log "No backup found for $target matching: $pattern" - return 1 -} - -manual_partial_rollback_default_pa() { - local pa="/etc/pulse/default.pa" - [ -f "$pa" ] || { log "Missing $pa, skipping manual rollback"; return 0; } - - backup_current "$pa" - - sed -i -E 's@^([[:space:]]*)#[[:space:]]*(set-default-(sink|source)[[:space:]]+.*es8388.*)$@\1\2@g' "$pa" - sed -i -E 's@^([[:space:]]*)#[[:space:]]*(load-module[[:space:]]+module-rescue-streams([[:space:]]|$).*)$@\1\2@g' "$pa" - - if grep -Eq '^[[:space:]]*load-module[[:space:]]+module-native-protocol-unix[[:space:]]*$' "$pa"; then - log "default.pa has plain module-native-protocol-unix entry. Original socket=/tmp/pulse-socket parameters cannot be reconstructed without backup." - fi - - log "Applied manual partial rollback to $pa" -} - -manual_partial_rollback_client_conf() { - local conf="/etc/pulse/client.conf" - [ -f "$conf" ] || { log "Missing $conf, skipping manual rollback"; return 0; } - - backup_current "$conf" - sed -i -E 's@^([[:space:]]*)#[[:space:]]*(default-server[[:space:]]*=[[:space:]]*unix:/tmp/pulse-socket[[:space:]]*)$@\1\2@g' "$conf" - log "Applied manual partial rollback to $conf" -} - -restart_audio_stack() { - if command -v systemctl >/dev/null 2>&1; then - systemctl restart pulseaudio.service >/dev/null 2>&1 || true - systemctl restart pipewire.service >/dev/null 2>&1 || true - systemctl restart wireplumber.service >/dev/null 2>&1 || true - fi - - if id itscreen >/dev/null 2>&1; then - pkill -u itscreen pulseaudio >/dev/null 2>&1 || true - fi - pkill pulseaudio >/dev/null 2>&1 || true - - log "Triggered audio service restart where available" -} - -show_summary() { - local pa="/etc/pulse/default.pa" - local conf="/etc/pulse/client.conf" - - echo - echo "Current PulseAudio-related lines:" - [ -f "$pa" ] && grep -nE 'es8388|module-rescue-streams|module-native-protocol-unix' "$pa" || true - [ -f "$conf" ] && grep -nE 'default-server' "$conf" || true - echo - echo "If audio still does not recover, reboot the device:" - echo " sudo reboot" -} - -main() { - require_root - log "Starting PulseAudio rollback" - - if ! restore_from_backup /etc/pulse/default.pa '/etc/pulse/default.pa.bak.*'; then - manual_partial_rollback_default_pa - fi - - if ! restore_from_backup /etc/pulse/client.conf '/etc/pulse/client.conf.bak.*'; then - manual_partial_rollback_client_conf - fi - - restart_audio_stack - show_summary - log "PulseAudio rollback finished" -} - -main "$@" diff --git a/stage_env/stage_env_install_no_pulse.sh b/stage_env/stage_env_install_no_pulse.sh index 4435901..014dbd3 100644 --- a/stage_env/stage_env_install_no_pulse.sh +++ b/stage_env/stage_env_install_no_pulse.sh @@ -573,7 +573,40 @@ ensure_gui_home_state() { done } +ensure_lightdm_iomatex_login() { + local dropin="/etc/lightdm/lightdm.conf.d/90-iomatex-autologin.conf" + local accounts_user_file="/var/lib/AccountsService/users/${IOM_USER}" + + install -d -m 0755 /etc/lightdm/lightdm.conf.d + write_if_changed "$dropin" 0644 </dev/null 2>&1; then log "Harden vendor user: youngfeel (lock password, disable shell, remove sudo)" soft_run "Lock password youngfeel" 10 /usr/bin/passwd -l youngfeel