commit 4dbe9e430b1e16ae921b7940d853bb7be96c5ba3 Author: Andrei Smaliak Date: Fri Mar 13 10:31:13 2026 +0400 Initial import of edge provisioning stages diff --git a/Source.list/source.sh b/Source.list/source.sh new file mode 100755 index 0000000..760f7cf --- /dev/null +++ b/Source.list/source.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +set -euo pipefail + +echo "=== Writing clean Debian 11 (bullseye) sources ===" + +sudo tee /etc/apt/sources.list >/dev/null <<'EOF' +deb http://deb.debian.org/debian bullseye main contrib non-free +deb http://deb.debian.org/debian bullseye-updates main contrib non-free +deb http://security.debian.org/debian-security bullseye-security main contrib non-free +EOF + +echo "=== Cleaning apt cache ===" +sudo apt clean + +echo "=== Updating package lists ===" +sudo apt update + +echo "=== Done ===" \ No newline at end of file diff --git a/Stage_1 (Mqtt)/Summary.md b/Stage_1 (Mqtt)/Summary.md new file mode 100755 index 0000000..c2c6223 --- /dev/null +++ b/Stage_1 (Mqtt)/Summary.md @@ -0,0 +1,10 @@ +Stage1 Result + +After Stage1: + +✔ Local MQTT operational +✔ Bridge auto-managed +✔ Namespace structured +✔ Watcher active +✔ Health supervision enabled +✔ Ready for IT-Screen client integration \ No newline at end of file diff --git a/Stage_1 (Mqtt)/iomatex@172.20.10.4 b/Stage_1 (Mqtt)/iomatex@172.20.10.4 new file mode 100755 index 0000000..6bccd72 --- /dev/null +++ b/Stage_1 (Mqtt)/iomatex@172.20.10.4 @@ -0,0 +1,543 @@ +#!/usr/bin/env bash +set -euo pipefail + +# --- Notepad++/Windows safety guards (BOM + CRLF) --- +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 in Notepad++." >&2 + exit 1 +fi + +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +export DEBIAN_FRONTEND=noninteractive + +LOG="/var/log/iomatex-stage1-mqtt.log" +mkdir -p /var/log >/dev/null 2>&1 || true +touch "$LOG" >/dev/null 2>&1 || true + +log() { + local line="[$(date -u +'%F %T UTC')] $*" + echo "$line" + echo "$line" >>"$LOG" 2>/dev/null || true +} + +step_n=0 +step() { + step_n=$((step_n+1)) + echo + echo "=== Step ${step_n}: $* ===" + log "STEP ${step_n}: $*" +} + +spinner() { + local pid="$1" + local msg="${2:-Working}" + local spin='|/-\' + local i=0 + + if command -v tput >/dev/null 2>&1 && [[ -t 1 ]]; then tput civis || true; fi + while kill -0 "$pid" 2>/dev/null; do + i=$(( (i+1) % 4 )) + if [[ -t 1 ]]; then printf "\r[%c] %s" "${spin:$i:1}" "$msg"; fi + sleep 0.12 + done + if [[ -t 1 ]]; then printf "\r[✓] %s\n" "$msg"; else echo "[✓] $msg"; fi + if command -v tput >/dev/null 2>&1 && [[ -t 1 ]]; then tput cnorm || true; fi +} + +run_bg() { local msg="$1"; shift; ( "$@" ) & local pid=$!; spinner "$pid" "$msg"; wait "$pid"; } + +need_root() { if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then echo "Run as root: sudo $0" >&2; exit 1; fi; } +need_root + +ENV_FILE="/etc/iomatex/mqtt_bridge.env" +MOSQ_MAIN="/etc/mosquitto/mosquitto.conf" +MAIN_SNIPPET="/etc/mosquitto/conf.d/01-iomatex-main-listener.conf" +APPLY="/usr/local/sbin/iomatex-mqtt-apply" +REMOTE_SET="/usr/local/sbin/iomatex-mqtt-remote-set" + +step "Install Mosquitto broker + clients" +run_bg "apt-get update" apt-get update +run_bg "install mosquitto + clients" apt-get install -y mosquitto mosquitto-clients +apt-get install -y netcat-openbsd >/dev/null 2>&1 || true + +step "Create directories and base env file (DO NOT wipe existing creds)" +mkdir -p /etc/iomatex +if [[ ! -f "$ENV_FILE" ]]; then + cat >"$ENV_FILE" <<'__IOMATEX_ENV__' +# IOMATEX MQTT bridge settings (parsed as key=value, NOT sourced) +# ASCII recommended. No spaces around '='. Values may contain spaces (we do not source this file). +ENABLE_BRIDGE=0 +REMOTE_HOST= +REMOTE_PORT=1883 +REMOTE_TLS=0 +REMOTE_USERNAME= +REMOTE_PASSWORD= +REMOTE_CLIENTID= +__IOMATEX_ENV__ + chmod 600 "$ENV_FILE" + chown root:root "$ENV_FILE" +else + chmod 600 "$ENV_FILE" || true + chown root:root "$ENV_FILE" || true +fi + +step "Ensure mosquitto.conf includes conf.d and write single source-of-truth listener snippet" +if ! grep -qE '^\s*include_dir\s+/etc/mosquitto/conf\.d\s*$' "$MOSQ_MAIN"; then + cp -a "$MOSQ_MAIN" "${MOSQ_MAIN}.bak.$(date -u +%Y%m%d%H%M%S)" + echo >>"$MOSQ_MAIN" + echo "include_dir /etc/mosquitto/conf.d" >>"$MOSQ_MAIN" +fi + +cat >"$MAIN_SNIPPET" <<'__IOMATEX_LISTENER__' +# IOMATEX managed main listener (single source of truth) +# Change bind here if needed: +# listener 1883 0.0.0.0 (LAN) +# listener 1883 127.0.0.1 (localhost only) +per_listener_settings true +listener 1883 0.0.0.0 +protocol mqtt +allow_anonymous true +log_dest syslog +__IOMATEX_LISTENER__ +chmod 644 "$MAIN_SNIPPET" +rm -f /etc/mosquitto/conf.d/00-iomatex-local.conf 2>/dev/null || true + +step "Install apply tool: iomatex-mqtt-apply (CLI; edits env; generates bridge; restarts mosquitto)" +cat >"$APPLY" <<'__IOMATEX_APPLY__' +#!/usr/bin/env bash +set -euo pipefail + +ENV_FILE="/etc/iomatex/mqtt_bridge.env" +BRIDGE_CONF="/etc/mosquitto/conf.d/50-iomatex-bridge.conf" +MAIN_SNIPPET="/etc/mosquitto/conf.d/01-iomatex-main-listener.conf" +STAMP="/run/iomatex-mqtt-apply.sha" + +log(){ echo "[$(date -u +'%F %T UTC')] $*"; } +die(){ echo "ERROR: $*" >&2; exit 1; } +require_root(){ [[ "${EUID:-$(id -u)}" -eq 0 ]] || die "Run as root (use sudo)."; } + +DEVICE_ID="$(hostname -s 2>/dev/null || hostname)" +DEFAULT_CLIENTID="${DEVICE_ID}-bridge" + +# In-memory settings loaded from env +ENABLE_BRIDGE="0" +REMOTE_HOST="" +REMOTE_PORT="1883" +REMOTE_TLS="0" +REMOTE_USERNAME="" +REMOTE_PASSWORD="" +REMOTE_CLIENTID="$DEFAULT_CLIENTID" + +usage(){ + cat <<'__USAGE__' +iomatex-mqtt-apply - Manage Mosquitto bridge via /etc/iomatex/mqtt_bridge.env + +Actions: + --print + --enable [--allow-anon] + --disable + --check (TCP connect to host:port before apply) + +Setters: + --set-host HOST + --set-port PORT + --set-tls 0|1 + --set-user USER + --set-pass PASS + --set-clientid ID + +Examples: + sudo iomatex-mqtt-apply --set-host dev.it-screen.com --set-user broadcaster --set-pass '***' --set-port 1883 --set-tls 0 --enable --check --print + sudo iomatex-mqtt-apply --disable --print +__USAGE__ +} + +ensure_env_file(){ + mkdir -p /etc/iomatex + if [[ ! -f "$ENV_FILE" ]]; then + cat >"$ENV_FILE" <<__ENV__ +ENABLE_BRIDGE=0 +REMOTE_HOST= +REMOTE_PORT=1883 +REMOTE_TLS=0 +REMOTE_USERNAME= +REMOTE_PASSWORD= +REMOTE_CLIENTID=${DEFAULT_CLIENTID} +__ENV__ + chmod 600 "$ENV_FILE" + chown root:root "$ENV_FILE" + fi + if head -c 3 "$ENV_FILE" 2>/dev/null | grep -q $'^\xEF\xBB\xBF'; then die "BOM detected in $ENV_FILE"; fi + if grep -q $'\r' "$ENV_FILE" 2>/dev/null; then die "CRLF detected in $ENV_FILE"; fi +} + +get_kv(){ + local k="$1" + local line + line="$(grep -m1 -E "^${k}=" "$ENV_FILE" 2>/dev/null || true)" + if [[ -z "$line" ]]; then echo ""; return 0; fi + echo "${line#${k}=}" +} + +load_env(){ + ENABLE_BRIDGE="$(get_kv ENABLE_BRIDGE)" + REMOTE_HOST="$(get_kv REMOTE_HOST)" + REMOTE_PORT="$(get_kv REMOTE_PORT)" + REMOTE_TLS="$(get_kv REMOTE_TLS)" + REMOTE_USERNAME="$(get_kv REMOTE_USERNAME)" + REMOTE_PASSWORD="$(get_kv REMOTE_PASSWORD)" + REMOTE_CLIENTID="$(get_kv REMOTE_CLIENTID)" + + : "${ENABLE_BRIDGE:=0}" + : "${REMOTE_HOST:=}" + : "${REMOTE_PORT:=1883}" + : "${REMOTE_TLS:=0}" + : "${REMOTE_USERNAME:=}" + : "${REMOTE_PASSWORD:=}" + : "${REMOTE_CLIENTID:=${DEFAULT_CLIENTID}}" +} + +validate_value(){ + local v="$1" + [[ "$v" != *$'\n'* && "$v" != *$'\r'* ]] || die "Invalid value contains newline/CR" +} + +set_kv(){ + local k="$1" v="$2" + validate_value "$v" + local tmp; tmp="$(mktemp)" + awk -v k="$k" -v v="$v" 'BEGIN{found=0} + $0 ~ "^"k"=" {print k"="v; found=1; next} + {print} + END{if(!found) print k"="v} + ' "$ENV_FILE" >"$tmp" + cat "$tmp" >"$ENV_FILE" + rm -f "$tmp" +} + +read_local_bind(){ + LOCAL_BIND="$(awk '($1=="listener" && $2=="1883"){print $3; exit}' "$MAIN_SNIPPET" 2>/dev/null || true)" + : "${LOCAL_BIND:=}" +} + +check_remote(){ + command -v nc >/dev/null 2>&1 || (apt-get update >/dev/null 2>&1 && apt-get install -y netcat-openbsd >/dev/null 2>&1) || true + [[ -n "$REMOTE_HOST" ]] || die "Cannot --check: REMOTE_HOST empty" + log "Checking TCP connect to ${REMOTE_HOST}:${REMOTE_PORT} ..." + nc -zvw3 "$REMOTE_HOST" "$REMOTE_PORT" >/dev/null 2>&1 || die "Remote not reachable: ${REMOTE_HOST}:${REMOTE_PORT}" + log "Remote reachable OK" +} + +write_bridge_conf(){ + rm -f "$BRIDGE_CONF" || true + + if [[ "$ENABLE_BRIDGE" != "1" ]]; then + log "ENABLE_BRIDGE=0 -> bridge disabled (no $BRIDGE_CONF)" + return 0 + fi + + [[ -n "$REMOTE_HOST" ]] || die "REMOTE_HOST is empty but bridge is enabled." + + cat >"$BRIDGE_CONF" <<__BRIDGE__ +# IOMATEX bridge to external MQTT +connection iomatex_bridge +address ${REMOTE_HOST}:${REMOTE_PORT} + +bridge_protocol_version mqttv311 +cleansession true +try_private true +notifications false + +clientid ${REMOTE_CLIENTID} +__BRIDGE__ + + if [[ -n "$REMOTE_USERNAME" ]]; then echo "remote_username ${REMOTE_USERNAME}" >>"$BRIDGE_CONF"; fi + if [[ -n "$REMOTE_PASSWORD" ]]; then echo "remote_password ${REMOTE_PASSWORD}" >>"$BRIDGE_CONF"; fi + + if [[ "${REMOTE_TLS}" == "1" ]]; then + cat >>"$BRIDGE_CONF" <<'__TLS__' +bridge_cafile /etc/ssl/certs/ca-certificates.crt +bridge_tls_version tlsv1.2 +__TLS__ + fi + + cat >>"$BRIDGE_CONF" <<__MAP__ + +# Topic mapping (hostname-root, inbound cmd only) +topic ${DEVICE_ID}/# out 0 "" "" +topic ${DEVICE_ID}/cmd/# in 0 "" "" +__MAP__ + + chmod 644 "$BRIDGE_CONF" || true +} + +restart_broker_if_changed(){ + systemctl daemon-reload >/dev/null 2>&1 || true + + local sha + sha="$( + ( sha256sum "$ENV_FILE" 2>/dev/null || true + sha256sum "$MAIN_SNIPPET" 2>/dev/null || true + sha256sum "$BRIDGE_CONF" 2>/dev/null || true ) | sha256sum | awk '{print $1}' + )" + + if [[ -f "$STAMP" ]] && [[ "$(cat "$STAMP" 2>/dev/null)" == "$sha" ]]; then + log "No config changes -> skip mosquitto restart" + return 0 + fi + + echo "$sha" >"$STAMP" 2>/dev/null || true + systemctl restart mosquitto + log "mosquitto restarted" +} + +report(){ + load_env + read_local_bind + echo + echo "=== IOMATEX MQTT BRIDGE REPORT ===" + echo "Hostname : ${DEVICE_ID}" + echo "Local bind : ${LOCAL_BIND}:1883 (source: ${MAIN_SNIPPET})" + echo "Remote host : ${REMOTE_HOST:-}" + echo "Remote port : ${REMOTE_PORT:-1883}" + echo "Remote TLS : ${REMOTE_TLS:-0}" + echo "Remote user : ${REMOTE_USERNAME:-}" + echo "Remote password : " + echo "Remote clientid : ${REMOTE_CLIENTID:-}" + echo "Bridge enabled : ${ENABLE_BRIDGE:-0}" + echo + echo "Bridge policy:" + echo " OUT: ${DEVICE_ID}/# -> ${DEVICE_ID}/#" + echo " IN : ${DEVICE_ID}/cmd/# -> ${DEVICE_ID}/cmd/#" + echo +} + +main(){ + require_root + ensure_env_file + load_env + + local WANT_PRINT=0 WANT_DISABLE=0 WANT_ENABLE=0 ALLOW_ANON=0 DO_CHECK=0 + local SET_HOST=0 SET_PORT=0 SET_TLS=0 SET_USER=0 SET_PASS=0 SET_CID=0 + local V_HOST="" V_PORT="" V_TLS="" V_USER="" V_PASS="" V_CID="" + + while [[ $# -gt 0 ]]; do + case "$1" in + --print) WANT_PRINT=1; shift;; + --disable) WANT_DISABLE=1; shift;; + --enable) WANT_ENABLE=1; shift;; + --allow-anon) ALLOW_ANON=1; shift;; + --check) DO_CHECK=1; shift;; + + --set-host) SET_HOST=1; V_HOST="${2-}"; shift 2;; + --set-port) SET_PORT=1; V_PORT="${2-}"; shift 2;; + --set-tls) SET_TLS=1; V_TLS="${2-}"; shift 2;; + --set-user) SET_USER=1; V_USER="${2-}"; shift 2;; + --set-pass) SET_PASS=1; V_PASS="${2-}"; shift 2;; + --set-clientid) SET_CID=1; V_CID="${2-}"; shift 2;; + + -h|--help) usage; exit 0;; + *) die "Unknown arg: $1 (use --help)";; + esac + done + + [[ "$SET_HOST" == "1" ]] && set_kv REMOTE_HOST "$V_HOST" + [[ "$SET_PORT" == "1" ]] && set_kv REMOTE_PORT "$V_PORT" + [[ "$SET_TLS" == "1" ]] && set_kv REMOTE_TLS "$V_TLS" + [[ "$SET_USER" == "1" ]] && set_kv REMOTE_USERNAME "$V_USER" + [[ "$SET_PASS" == "1" ]] && set_kv REMOTE_PASSWORD "$V_PASS" + [[ "$SET_CID" == "1" ]] && set_kv REMOTE_CLIENTID "$V_CID" + + chmod 600 "$ENV_FILE" || true + chown root:root "$ENV_FILE" || true + + load_env + + if [[ "$WANT_DISABLE" == "1" ]]; then + set_kv ENABLE_BRIDGE "0" + load_env + fi + + if [[ "$WANT_ENABLE" == "1" ]]; then + [[ -n "$REMOTE_HOST" ]] || die "Cannot enable: REMOTE_HOST empty" + if [[ "$ALLOW_ANON" == "0" ]]; then + [[ -n "$REMOTE_USERNAME" ]] || die "Cannot enable: REMOTE_USERNAME empty (or use --allow-anon)" + [[ -n "$REMOTE_PASSWORD" ]] || die "Cannot enable: REMOTE_PASSWORD empty (or use --allow-anon)" + fi + set_kv ENABLE_BRIDGE "1" + load_env + fi + + if [[ "$DO_CHECK" == "1" ]]; then + check_remote + fi + + write_bridge_conf + restart_broker_if_changed + + if [[ "$WANT_PRINT" == "1" ]]; then + report + else + log "Applied. enabled=${ENABLE_BRIDGE} remote=${REMOTE_HOST}:${REMOTE_PORT} hostname=${DEVICE_ID}" + fi +} + +main "$@" +__IOMATEX_APPLY__ +chmod 0755 "$APPLY" +chown root:root "$APPLY" + +step "Install interactive remote-set tool (wrapper over iomatex-mqtt-apply; does not wipe on empty input)" +cat >"$REMOTE_SET" <<'__IOMATEX_REMOTE_SET__' +#!/usr/bin/env bash +set -euo pipefail + +require_root() { if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then echo "Run as root: sudo iomatex-mqtt-remote-set" >&2; exit 1; fi; } +require_root + +ENV_FILE="/etc/iomatex/mqtt_bridge.env" + +get_kv(){ + local k="$1" line + line="$(grep -m1 -E "^${k}=" "$ENV_FILE" 2>/dev/null || true)" + [[ -n "$line" ]] && echo "${line#${k}=}" || echo "" +} + +REMOTE_HOST="$(get_kv REMOTE_HOST)" +REMOTE_PORT="$(get_kv REMOTE_PORT)"; : "${REMOTE_PORT:=1883}" +REMOTE_TLS="$(get_kv REMOTE_TLS)"; : "${REMOTE_TLS:=0}" +REMOTE_USERNAME="$(get_kv REMOTE_USERNAME)" + +prompt() { local label="$1" current="$2" input; read -r -p "${label} (current: ${current:-empty}): " input; echo "${input}"; } +prompt_port() { local label="$1" current="$2" input; read -r -p "${label} (current: ${current:-1883}, default 1883): " input; [[ -z "$input" ]] && echo "${current:-1883}" || echo "$input"; } +prompt_tls() { local label="$1" current="$2" input; read -r -p "${label} [0/1] (current: ${current:-0}, default 0): " input; [[ -z "$input" ]] && echo "${current:-0}" || echo "$input"; } + +echo +echo "Enter external MQTT connection." +echo "NOTE: This tool calls iomatex-mqtt-apply (single source of truth)." +echo "TIP : Press Enter to KEEP current values." +echo + +h="$(prompt "REMOTE_HOST" "$REMOTE_HOST")" +u="$(prompt "REMOTE_USERNAME" "$REMOTE_USERNAME")" +read -r -s -p "REMOTE_PASSWORD (hidden; Enter to keep current): " p; echo +pr="$(prompt_port "REMOTE_PORT" "$REMOTE_PORT")" +tls="$(prompt_tls "REMOTE_TLS" "$REMOTE_TLS")" + +args=() +[[ -n "$h" ]] && args+=(--set-host "$h") +[[ -n "$u" ]] && args+=(--set-user "$u") +[[ -n "$p" ]] && args+=(--set-pass "$p") +args+=(--set-port "$pr") +args+=(--set-tls "$tls") +args+=(--enable --print) + +exec /usr/local/sbin/iomatex-mqtt-apply "${args[@]}" +__IOMATEX_REMOTE_SET__ +chmod 0755 "$REMOTE_SET" +chown root:root "$REMOTE_SET" + +step "Allow itscreen user to run iomatex-mqtt-apply via sudo (NOPASSWD)" +install -d -m 0755 /etc/sudoers.d +cat >/etc/sudoers.d/90-iomatex-mqtt-apply <<'__IOMATEX_SUDOERS__' +# Allow itscreen to manage MQTT bridge without password +itscreen ALL=(root) NOPASSWD: /usr/local/sbin/iomatex-mqtt-apply +__IOMATEX_SUDOERS__ +chmod 0440 /etc/sudoers.d/90-iomatex-mqtt-apply +if command -v visudo >/dev/null 2>&1; then visudo -cf /etc/sudoers.d/90-iomatex-mqtt-apply >/dev/null; fi + +step "Create systemd watcher: auto-apply on env changes" +cat >/etc/systemd/system/iomatex-mqtt-bridge.service <<'__IOMATEX_PATH_SVC__' +[Unit] +Description=IOMATEX MQTT Apply (regen mosquitto conf) +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/iomatex-mqtt-apply +__IOMATEX_PATH_SVC__ + +cat >/etc/systemd/system/iomatex-mqtt-bridge.path <<'__IOMATEX_PATH__' +[Unit] +Description=Watch /etc/iomatex/mqtt_bridge.env and re-apply mosquitto config + +[Path] +PathChanged=/etc/iomatex/mqtt_bridge.env + +[Install] +WantedBy=multi-user.target +__IOMATEX_PATH__ + +step "Create health timer (publishes under hostname root)" +cat >/usr/local/sbin/iomatex-mqtt-health.sh <<'__IOMATEX_HEALTH_SH__' +#!/usr/bin/env bash +set -euo pipefail +if ! systemctl is-active --quiet mosquitto; then systemctl start mosquitto || systemctl restart mosquitto || true; fi +ts="$(date -u +'%F %T UTC')" +h="$(hostname -s)" +mosquitto_pub -h 127.0.0.1 -t "${h}/health/ping" -m "ping ${ts}" >/dev/null 2>&1 || true +__IOMATEX_HEALTH_SH__ +chmod 0755 /usr/local/sbin/iomatex-mqtt-health.sh +chown root:root /usr/local/sbin/iomatex-mqtt-health.sh + +cat >/etc/systemd/system/iomatex-mqtt-health.service <<'__IOMATEX_HEALTH_SVC__' +[Unit] +Description=IOMATEX MQTT health check + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/iomatex-mqtt-health.sh +__IOMATEX_HEALTH_SVC__ + +cat >/etc/systemd/system/iomatex-mqtt-health.timer <<'__IOMATEX_HEALTH_TIMER__' +[Unit] +Description=Run IOMATEX MQTT health check every minute + +[Timer] +OnBootSec=30s +OnUnitActiveSec=60s +AccuracySec=15s +Persistent=true + +[Install] +WantedBy=timers.target +__IOMATEX_HEALTH_TIMER__ + +step "Enable services, apply config now" +systemctl daemon-reload +systemctl enable mosquitto >/dev/null 2>&1 || true +systemctl enable --now iomatex-mqtt-bridge.path +systemctl enable --now iomatex-mqtt-health.timer +/usr/local/sbin/iomatex-mqtt-apply --print || true + +step "Cleanup any temporary debug config (if exists)" +rm -f /etc/mosquitto/conf.d/99-iomatex-debug.conf >/dev/null 2>&1 || true + +step "Print quick status + tips" +H="$(hostname -s)" +BIND="$(awk '($1=="listener" && $2=="1883"){print $3; exit}' /etc/mosquitto/conf.d/01-iomatex-main-listener.conf 2>/dev/null || true)" +echo +echo "Local broker listener (SOURCE OF TRUTH): /etc/mosquitto/conf.d/01-iomatex-main-listener.conf" +echo " listener 1883 ${BIND:-}" +echo +echo "Effective listeners (runtime):" +ss -lntp 2>/dev/null | grep -E ":(1883)\b" || true +echo +echo "ENV: $ENV_FILE" +grep -n -E '^(ENABLE_BRIDGE|REMOTE_HOST|REMOTE_PORT|REMOTE_TLS|REMOTE_USERNAME|REMOTE_CLIENTID|REMOTE_PASSWORD)=' "$ENV_FILE" 2>/dev/null | sed -E 's/^(REMOTE_PASSWORD=).*/\1/' || true +echo +echo "Bridge conf:" +ls -la /etc/mosquitto/conf.d/50-iomatex-bridge.conf 2>/dev/null || echo " (not present: bridge disabled)" +echo +echo "Manual remote set + report:" +echo " sudo iomatex-mqtt-remote-set" +echo +echo "Non-interactive apply example (for itscreen):" +echo " sudo iomatex-mqtt-apply --set-host dev.it-screen.com --set-user broadcaster --set-pass \"PASS\" --set-port 1883 --set-tls 0 --enable --check --print" +echo +log "Stage1 MQTT finished successfully." \ No newline at end of file diff --git a/Stage_1 (Mqtt)/stage_mqtt.sh b/Stage_1 (Mqtt)/stage_mqtt.sh new file mode 100755 index 0000000..979b052 --- /dev/null +++ b/Stage_1 (Mqtt)/stage_mqtt.sh @@ -0,0 +1,686 @@ +#!/usr/bin/env bash +set -euo pipefail + +# --- Notepad++/Windows safety guards (BOM + CRLF) --- +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 in Notepad++." >&2 + exit 1 +fi + +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +export DEBIAN_FRONTEND=noninteractive + +LOG="/var/log/iomatex-stage1-mqtt.log" +mkdir -p /var/log >/dev/null 2>&1 || true +touch "$LOG" >/dev/null 2>&1 || true + +log() { + local line="[$(date -u +'%F %T UTC')] $*" + echo "$line" + echo "$line" >>"$LOG" 2>/dev/null || true +} + +step_n=0 +step() { + step_n=$((step_n+1)) + echo + echo "=== Step ${step_n}: $* ===" + log "STEP ${step_n}: $*" +} + +spinner() { + local pid="$1" + local msg="${2:-Working}" + local spin='|/-\' + local i=0 + if command -v tput >/dev/null 2>&1 && [[ -t 1 ]]; then tput civis || true; fi + while kill -0 "$pid" 2>/dev/null; do + i=$(( (i+1) % 4 )) + if [[ -t 1 ]]; then printf "\r[%c] %s" "${spin:$i:1}" "$msg"; fi + sleep 0.12 + done + if [[ -t 1 ]]; then printf "\r[✓] %s\n" "$msg"; else echo "[✓] $msg"; fi + if command -v tput >/dev/null 2>&1 && [[ -t 1 ]]; then tput cnorm || true; fi +} + +run_bg() { + local msg="$1" + shift + ( "$@" ) & + local pid=$! + spinner "$pid" "$msg" + wait "$pid" +} + +need_root() { + if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then + echo "Run as root: sudo $0" >&2 + exit 1 + fi +} +need_root + +HOSTNAME_SHORT="$(hostname -s 2>/dev/null || hostname)" + +ENV_FILE="/etc/iomatex/mqtt_bridge.env" +MOSQ_MAIN="/etc/mosquitto/mosquitto.conf" +MAIN_SNIPPET="/etc/mosquitto/conf.d/01-iomatex-main-listener.conf" +BRIDGE_CONF="/etc/mosquitto/conf.d/50-iomatex-bridge.conf" +APPLY="/usr/local/sbin/iomatex-mqtt-apply" +REMOTE_SET="/usr/local/sbin/iomatex-mqtt-remote-set" +HEALTH_SH="/usr/local/sbin/iomatex-mqtt-health.sh" + +step "Full cleanup of previous MQTT/IOMATEX artifacts" +systemctl stop mosquitto 2>/dev/null || true +systemctl stop iomatex-mqtt-bridge.path iomatex-mqtt-bridge.service 2>/dev/null || true +systemctl stop iomatex-mqtt-apply.path iomatex-mqtt-apply.service 2>/dev/null || true +systemctl stop iomatex-mqtt-health.timer iomatex-mqtt-health.service 2>/dev/null || true + +systemctl disable iomatex-mqtt-bridge.path 2>/dev/null || true +systemctl disable iomatex-mqtt-apply.path 2>/dev/null || true +systemctl disable iomatex-mqtt-health.timer 2>/dev/null || true + +rm -f /etc/mosquitto/conf.d/00-iomatex-local.conf 2>/dev/null || true +rm -f /etc/mosquitto/conf.d/01-iomatex-main-listener.conf 2>/dev/null || true +rm -f /etc/mosquitto/conf.d/20-iomatex-bridge.conf 2>/dev/null || true +rm -f /etc/mosquitto/conf.d/30-iomatex-bridge.conf 2>/dev/null || true +rm -f /etc/mosquitto/conf.d/40-iomatex-bridge.conf 2>/dev/null || true +rm -f /etc/mosquitto/conf.d/50-iomatex-bridge.conf 2>/dev/null || true +rm -f /etc/mosquitto/conf.d/60-iomatex-bridge.conf 2>/dev/null || true +rm -f /etc/mosquitto/conf.d/99-iomatex-debug.conf 2>/dev/null || true +rm -f /etc/mosquitto/conf.d/zz-iomatex-bridge.conf 2>/dev/null || true + +rm -f /etc/iomatex/mqtt_bridge.env 2>/dev/null || true +rm -f /usr/local/sbin/iomatex-mqtt-apply 2>/dev/null || true +rm -f /usr/local/sbin/iomatex-mqtt-remote-set 2>/dev/null || true +rm -f /usr/local/sbin/iomatex-mqtt-health.sh 2>/dev/null || true +rm -f /usr/local/sbin/iomatex-mqtt-bridge-apply 2>/dev/null || true +rm -f /usr/local/sbin/iomatex-mqtt-bridge 2>/dev/null || true + +rm -f /etc/systemd/system/iomatex-mqtt-apply.service 2>/dev/null || true +rm -f /etc/systemd/system/iomatex-mqtt-apply.path 2>/dev/null || true +rm -f /etc/systemd/system/iomatex-mqtt-bridge.service 2>/dev/null || true +rm -f /etc/systemd/system/iomatex-mqtt-bridge.path 2>/dev/null || true +rm -f /etc/systemd/system/iomatex-mqtt-health.service 2>/dev/null || true +rm -f /etc/systemd/system/iomatex-mqtt-health.timer 2>/dev/null || true + +rm -f /etc/sudoers.d/90-iomatex-mqtt-apply 2>/dev/null || true + +rm -f /var/lib/mosquitto/mosquitto.db /var/lib/mosquitto/*.db 2>/dev/null || true +rm -f /run/iomatex-mqtt-apply.sha 2>/dev/null || true +rm -f /var/log/mosquitto/mosquitto.log /var/log/iomatex-stage1-mqtt.log 2>/dev/null || true + +systemctl daemon-reload >/dev/null 2>&1 || true +touch "$LOG" >/dev/null 2>&1 || true +log "OK: cleaned mosquitto configs, iomatex tools/env, mosquitto DB, systemd units, and logs. Ready for clean install." + +step "Install Mosquitto broker + clients" +run_bg "apt-get update" apt-get update +run_bg "install mosquitto + clients" apt-get install -y mosquitto mosquitto-clients +apt-get install -y netcat-openbsd >/dev/null 2>&1 || true + +step "Create directories and base env file" +mkdir -p /etc/iomatex +cat >"$ENV_FILE" <<__IOMATEX_ENV__ +# IOMATEX MQTT bridge settings (parsed as key=value, NOT sourced) +# ASCII recommended. No spaces around '='. Values may contain spaces (we do not source this file). +ENABLE_BRIDGE=0 +REMOTE_HOST= +REMOTE_PORT=1883 +REMOTE_TLS=0 +REMOTE_USERNAME= +REMOTE_PASSWORD= +REMOTE_CLIENTID=${HOSTNAME_SHORT} +LEGACY_ITSCREEN_TREE=1 +BRIDGE_BASE_TOPIC=v1/edge +__IOMATEX_ENV__ +chmod 600 "$ENV_FILE" +chown root:root "$ENV_FILE" + +step "Ensure mosquitto.conf includes conf.d and write single source-of-truth listener snippet" +if ! grep -qE '^\s*include_dir\s+/etc/mosquitto/conf\.d\s*$' "$MOSQ_MAIN"; then + cp -a "$MOSQ_MAIN" "${MOSQ_MAIN}.bak.$(date -u +%Y%m%d%H%M%S)" + echo >>"$MOSQ_MAIN" + echo "include_dir /etc/mosquitto/conf.d" >>"$MOSQ_MAIN" +fi + +cat >"$MAIN_SNIPPET" <<'__IOMATEX_LISTENER__' +# IOMATEX managed main listener (single source of truth) +per_listener_settings true +listener 1883 0.0.0.0 +protocol mqtt +allow_anonymous true +log_dest syslog +__IOMATEX_LISTENER__ +chmod 644 "$MAIN_SNIPPET" + +step "Install apply tool: iomatex-mqtt-apply" +cat >"$APPLY" <<'__IOMATEX_APPLY__' +#!/usr/bin/env bash +set -euo pipefail + +ENV_FILE="/etc/iomatex/mqtt_bridge.env" +BRIDGE_CONF="/etc/mosquitto/conf.d/50-iomatex-bridge.conf" +MAIN_SNIPPET="/etc/mosquitto/conf.d/01-iomatex-main-listener.conf" +STAMP="/run/iomatex-mqtt-apply.sha" + +log(){ echo "[$(date -u +'%F %T UTC')] $*"; } +die(){ echo "ERROR: $*" >&2; exit 1; } +require_root(){ [[ "${EUID:-$(id -u)}" -eq 0 ]] || die "Run as root (use sudo)."; } + +DEVICE_ID="$(hostname -s 2>/dev/null || hostname)" +DEFAULT_CLIENTID="${DEVICE_ID}" + +ENABLE_BRIDGE="0" +REMOTE_HOST="" +REMOTE_PORT="1883" +REMOTE_TLS="0" +REMOTE_USERNAME="" +REMOTE_PASSWORD="" +REMOTE_CLIENTID="$DEFAULT_CLIENTID" +LEGACY_ITSCREEN_TREE="1" +BRIDGE_BASE_TOPIC="v1/edge" + +usage(){ + cat <<'__USAGE__' +iomatex-mqtt-apply - Manage Mosquitto bridge via /etc/iomatex/mqtt_bridge.env + +Actions: + --print + --enable [--allow-anon] + --disable + --check + --checkpass + +Setters: + --set-host HOST + --set-port PORT + --set-tls 0|1 + --set-user USER + --set-pass PASS + --set-clientid ID + --set-base-topic TOPIC + --legacy-itscreen 0|1 + +Examples: + sudo iomatex-mqtt-apply --set-host dev.it-screen.com --set-user broadcaster --set-pass '***' --set-port 1883 --set-tls 0 --set-base-topic v1/edge --enable --check --print + sudo iomatex-mqtt-apply --disable --print +__USAGE__ +} + +ensure_env_file(){ + mkdir -p /etc/iomatex + if [[ ! -f "$ENV_FILE" ]]; then + cat >"$ENV_FILE" <<__ENV__ +ENABLE_BRIDGE=0 +REMOTE_HOST= +REMOTE_PORT=1883 +REMOTE_TLS=0 +REMOTE_USERNAME= +REMOTE_PASSWORD= +REMOTE_CLIENTID=${DEFAULT_CLIENTID} +LEGACY_ITSCREEN_TREE=1 +BRIDGE_BASE_TOPIC=v1/edge +__ENV__ + chmod 600 "$ENV_FILE" + chown root:root "$ENV_FILE" + fi + if head -c 3 "$ENV_FILE" 2>/dev/null | grep -q $'^\xEF\xBB\xBF'; then die "BOM detected in $ENV_FILE"; fi + if grep -q $'\r' "$ENV_FILE" 2>/dev/null; then die "CRLF detected in $ENV_FILE"; fi + grep -qE '^LEGACY_ITSCREEN_TREE=' "$ENV_FILE" || echo "LEGACY_ITSCREEN_TREE=1" >>"$ENV_FILE" + grep -qE '^REMOTE_CLIENTID=' "$ENV_FILE" || echo "REMOTE_CLIENTID=${DEFAULT_CLIENTID}" >>"$ENV_FILE" + grep -qE '^BRIDGE_BASE_TOPIC=' "$ENV_FILE" || echo "BRIDGE_BASE_TOPIC=v1/edge" >>"$ENV_FILE" +} + +get_kv(){ + local k="$1" line + line="$(grep -m1 -E "^${k}=" "$ENV_FILE" 2>/dev/null || true)" + [[ -n "$line" ]] && echo "${line#${k}=}" || echo "" +} + +load_env(){ + ENABLE_BRIDGE="$(get_kv ENABLE_BRIDGE)"; : "${ENABLE_BRIDGE:=0}" + REMOTE_HOST="$(get_kv REMOTE_HOST)"; : "${REMOTE_HOST:=}" + REMOTE_PORT="$(get_kv REMOTE_PORT)"; : "${REMOTE_PORT:=1883}" + REMOTE_TLS="$(get_kv REMOTE_TLS)"; : "${REMOTE_TLS:=0}" + REMOTE_USERNAME="$(get_kv REMOTE_USERNAME)"; : "${REMOTE_USERNAME:=}" + REMOTE_PASSWORD="$(get_kv REMOTE_PASSWORD)"; : "${REMOTE_PASSWORD:=}" + REMOTE_CLIENTID="$(get_kv REMOTE_CLIENTID)"; : "${REMOTE_CLIENTID:=${DEFAULT_CLIENTID}}" + LEGACY_ITSCREEN_TREE="$(get_kv LEGACY_ITSCREEN_TREE)"; : "${LEGACY_ITSCREEN_TREE:=1}" + BRIDGE_BASE_TOPIC="$(get_kv BRIDGE_BASE_TOPIC)"; : "${BRIDGE_BASE_TOPIC:=v1/edge}" +} + +validate_value(){ + local v="$1" + [[ "$v" != *$'\n'* && "$v" != *$'\r'* ]] || die "Invalid value contains newline/CR" +} + +set_kv(){ + local k="$1" v="$2" + validate_value "$v" + local tmp; tmp="$(mktemp)" + awk -v k="$k" -v v="$v" 'BEGIN{found=0} + $0 ~ "^"k"=" {print k"="v; found=1; next} + {print} + END{if(!found) print k"="v} + ' "$ENV_FILE" >"$tmp" + cat "$tmp" >"$ENV_FILE" + rm -f "$tmp" +} + +read_local_bind(){ + LOCAL_BIND="$(awk '($1=="listener" && $2=="1883"){print $3; exit}' "$MAIN_SNIPPET" 2>/dev/null || true)" + : "${LOCAL_BIND:=}" +} + +check_remote(){ + command -v nc >/dev/null 2>&1 || (apt-get update >/dev/null 2>&1 && apt-get install -y netcat-openbsd >/dev/null 2>&1) || true + [[ -n "$REMOTE_HOST" ]] || die "Cannot --check: REMOTE_HOST empty" + log "Checking TCP connect to ${REMOTE_HOST}:${REMOTE_PORT} ..." + nc -zvw3 "$REMOTE_HOST" "$REMOTE_PORT" >/dev/null 2>&1 || die "Remote not reachable: ${REMOTE_HOST}:${REMOTE_PORT}" + log "Remote reachable OK" +} + +write_bridge_conf(){ + rm -f "$BRIDGE_CONF" || true + + if [[ "$ENABLE_BRIDGE" != "1" ]]; then + log "ENABLE_BRIDGE=0 -> bridge disabled (no $BRIDGE_CONF)" + return 0 + fi + + [[ -n "$REMOTE_HOST" ]] || die "REMOTE_HOST is empty but bridge is enabled." + + cat >"$BRIDGE_CONF" <<__BRIDGE__ +# IOMATEX bridge to external MQTT +connection iomatex_bridge +address ${REMOTE_HOST}:${REMOTE_PORT} + +bridge_protocol_version mqttv311 +cleansession true +try_private true +notifications false + +clientid ${REMOTE_CLIENTID} +__BRIDGE__ + + [[ -n "$REMOTE_USERNAME" ]] && echo "remote_username ${REMOTE_USERNAME}" >>"$BRIDGE_CONF" + [[ -n "$REMOTE_PASSWORD" ]] && echo "remote_password ${REMOTE_PASSWORD}" >>"$BRIDGE_CONF" + + if [[ "${REMOTE_TLS}" == "1" ]]; then + cat >>"$BRIDGE_CONF" <<'__TLS__' +bridge_cafile /etc/ssl/certs/ca-certificates.crt +bridge_tls_version tlsv1.2 +__TLS__ + fi + + cat >>"$BRIDGE_CONF" <<'__MAP__' + +# Topic mapping (IOMATEX v1 edge contract) +topic v1/edge/# out 0 "" "" +topic v1/edge/# in 0 "" "" +__MAP__ + + if [[ "${LEGACY_ITSCREEN_TREE}" == "1" ]]; then + cat >>"$BRIDGE_CONF" <<'__LEGACY_ITSCREEN__' + +# Legacy contract: full it-screen tree (bi-directional) +topic it-screen/# out 0 "" "" +topic it-screen/# in 0 "" "" +__LEGACY_ITSCREEN__ + fi + + cat >>"$BRIDGE_CONF" <<'__LEGACY_IOMATEX__' + +# Legacy contract: full iomatex tree (bi-directional) +topic iomatex/# out 0 "" "" +topic iomatex/# in 0 "" "" +__LEGACY_IOMATEX__ + + chmod 644 "$BRIDGE_CONF" || true +} + +restart_broker_if_changed(){ + systemctl daemon-reload >/dev/null 2>&1 || true + + local sha + sha="$( + ( sha256sum "$ENV_FILE" 2>/dev/null || true + sha256sum "$MAIN_SNIPPET" 2>/dev/null || true + sha256sum "$BRIDGE_CONF" 2>/dev/null || true ) | sha256sum | awk '{print $1}' + )" + + if [[ -f "$STAMP" ]] && [[ "$(cat "$STAMP" 2>/dev/null)" == "$sha" ]]; then + log "No config changes -> skip mosquitto restart" + return 0 + fi + + echo "$sha" >"$STAMP" 2>/dev/null || true + systemctl restart mosquitto + log "mosquitto restarted" +} + +report(){ + load_env + read_local_bind + echo + echo "=== IOMATEX MQTT BRIDGE REPORT ===" + echo "Hostname : ${DEVICE_ID}" + echo "Local bind : ${LOCAL_BIND}:1883 (source: ${MAIN_SNIPPET})" + echo "Remote host : ${REMOTE_HOST:-}" + echo "Remote port : ${REMOTE_PORT:-1883}" + echo "Remote TLS : ${REMOTE_TLS:-0}" + echo "Remote user : ${REMOTE_USERNAME:-}" + echo "Remote password : " + echo "Remote clientid : ${REMOTE_CLIENTID:-}" + echo "Bridge enabled : ${ENABLE_BRIDGE:-0}" + echo "Legacy it-screen: ${LEGACY_ITSCREEN_TREE:-0}" + echo "Base topic : ${BRIDGE_BASE_TOPIC:-v1/edge}" + echo + echo "Bridge policy:" + echo " OUT: v1/edge/#" + echo " IN : v1/edge/#" + if [[ "${LEGACY_ITSCREEN_TREE:-0}" == "1" ]]; then + echo " OUT: it-screen/#" + echo " IN : it-screen/#" + fi + echo " OUT: iomatex/#" + echo " IN : iomatex/#" + echo +} + +main(){ + require_root + ensure_env_file + load_env + + local WANT_PRINT=0 WANT_DISABLE=0 WANT_ENABLE=0 ALLOW_ANON=0 DO_CHECK=0 DO_CHECKPASS=0 + local SET_HOST=0 SET_PORT=0 SET_TLS=0 SET_USER=0 SET_PASS=0 SET_CID=0 SET_LEG=0 SET_BASE=0 + local V_HOST="" V_PORT="" V_TLS="" V_USER="" V_PASS="" V_CID="" V_LEG="" V_BASE="" + + while [[ $# -gt 0 ]]; do + case "$1" in + --print) WANT_PRINT=1; shift;; + --disable) WANT_DISABLE=1; shift;; + --enable) WANT_ENABLE=1; shift;; + --allow-anon) ALLOW_ANON=1; shift;; + --check) DO_CHECK=1; shift;; + --checkpass) DO_CHECKPASS=1; shift;; + --set-host) SET_HOST=1; V_HOST="${2-}"; shift 2;; + --set-port) SET_PORT=1; V_PORT="${2-}"; shift 2;; + --set-tls) SET_TLS=1; V_TLS="${2-}"; shift 2;; + --set-user) SET_USER=1; V_USER="${2-}"; shift 2;; + --set-pass) SET_PASS=1; V_PASS="${2-}"; shift 2;; + --set-clientid) SET_CID=1; V_CID="${2-}"; shift 2;; + --set-base-topic) SET_BASE=1; V_BASE="${2-}"; shift 2;; + --legacy-itscreen) SET_LEG=1; V_LEG="${2-}"; shift 2;; + -h|--help) usage; exit 0;; + *) die "Unknown arg: $1 (use --help)";; + esac + done + + [[ "$SET_HOST" == "1" ]] && set_kv REMOTE_HOST "$V_HOST" + [[ "$SET_PORT" == "1" ]] && set_kv REMOTE_PORT "$V_PORT" + [[ "$SET_TLS" == "1" ]] && set_kv REMOTE_TLS "$V_TLS" + [[ "$SET_USER" == "1" ]] && set_kv REMOTE_USERNAME "$V_USER" + [[ "$SET_PASS" == "1" ]] && set_kv REMOTE_PASSWORD "$V_PASS" + [[ "$SET_CID" == "1" ]] && set_kv REMOTE_CLIENTID "$V_CID" + [[ "$SET_BASE" == "1" ]] && set_kv BRIDGE_BASE_TOPIC "$V_BASE" + [[ "$SET_LEG" == "1" ]] && set_kv LEGACY_ITSCREEN_TREE "$V_LEG" + + chmod 600 "$ENV_FILE" || true + chown root:root "$ENV_FILE" || true + + load_env + + if [[ "$DO_CHECKPASS" == "1" ]]; then + local input_pass="" + IFS= read -r -s input_pass || true + [[ -n "${REMOTE_PASSWORD:-}" ]] || exit 1 + [[ "$input_pass" == "$REMOTE_PASSWORD" ]] && exit 0 || exit 2 + fi + + if [[ "$WANT_DISABLE" == "1" ]]; then + set_kv ENABLE_BRIDGE "0" + load_env + fi + + if [[ "$WANT_ENABLE" == "1" ]]; then + [[ -n "$REMOTE_HOST" ]] || die "Cannot enable: REMOTE_HOST empty" + if [[ "$ALLOW_ANON" == "0" ]]; then + [[ -n "$REMOTE_USERNAME" ]] || die "Cannot enable: REMOTE_USERNAME empty (or use --allow-anon)" + [[ -n "$REMOTE_PASSWORD" ]] || die "Cannot enable: REMOTE_PASSWORD empty (or use --allow-anon)" + fi + set_kv ENABLE_BRIDGE "1" + load_env + fi + + [[ "$DO_CHECK" == "1" ]] && check_remote + + write_bridge_conf + restart_broker_if_changed + + if [[ "$WANT_PRINT" == "1" ]]; then + report + else + log "Applied. enabled=${ENABLE_BRIDGE} legacy_it_screen=${LEGACY_ITSCREEN_TREE} remote=${REMOTE_HOST}:${REMOTE_PORT} clientid=${REMOTE_CLIENTID} hostname=${DEVICE_ID} base_topic=${BRIDGE_BASE_TOPIC:-v1/edge}" + fi +} + +main "$@" +__IOMATEX_APPLY__ +chmod 0755 "$APPLY" +chown root:root "$APPLY" + +step "Install interactive remote-set tool" +cat >"$REMOTE_SET" <<'__IOMATEX_REMOTE_SET__' +#!/usr/bin/env bash +set -euo pipefail + +require_root() { + if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then + echo "Run as root: sudo iomatex-mqtt-remote-set" >&2 + exit 1 + fi +} +require_root + +ENV_FILE="/etc/iomatex/mqtt_bridge.env" + +get_kv(){ + local k="$1" line + line="$(grep -m1 -E "^${k}=" "$ENV_FILE" 2>/dev/null || true)" + [[ -n "$line" ]] && echo "${line#${k}=}" || echo "" +} + +REMOTE_HOST="$(get_kv REMOTE_HOST)" +REMOTE_PORT="$(get_kv REMOTE_PORT)"; : "${REMOTE_PORT:=1883}" +REMOTE_TLS="$(get_kv REMOTE_TLS)"; : "${REMOTE_TLS:=0}" +REMOTE_USERNAME="$(get_kv REMOTE_USERNAME)" +LEGACY="$(get_kv LEGACY_ITSCREEN_TREE)"; : "${LEGACY:=1}" +BASE_TOPIC="$(get_kv BRIDGE_BASE_TOPIC)"; : "${BASE_TOPIC:=v1/edge}" + +prompt() { local label="$1" current="$2" input; read -r -p "${label} (current: ${current:-empty}): " input; echo "${input}"; } +prompt_port() { local label="$1" current="$2" input; read -r -p "${label} (current: ${current:-1883}, default 1883): " input; [[ -z "$input" ]] && echo "${current:-1883}" || echo "$input"; } +prompt_tls() { local label="$1" current="$2" input; read -r -p "${label} [0/1] (current: ${current:-0}, default 0): " input; [[ -z "$input" ]] && echo "${current:-0}" || echo "$input"; } +prompt_legacy() { local label="$1" current="$2" input; read -r -p "${label} [0/1] (current: ${current:-1}, default 1): " input; [[ -z "$input" ]] && echo "${current:-1}" || echo "$input"; } + +echo +echo "Enter external MQTT connection." +echo "NOTE: This tool calls iomatex-mqtt-apply (single source of truth)." +echo "TIP : Press Enter to KEEP current values." +echo + +h="$(prompt "REMOTE_HOST" "$REMOTE_HOST")" +u="$(prompt "REMOTE_USERNAME" "$REMOTE_USERNAME")" +read -r -s -p "REMOTE_PASSWORD (hidden; Enter to keep current): " p; echo +pr="$(prompt_port "REMOTE_PORT" "$REMOTE_PORT")" +tls="$(prompt_tls "REMOTE_TLS" "$REMOTE_TLS")" +leg="$(prompt_legacy "LEGACY_ITSCREEN_TREE (mirror it-screen/# both ways)" "$LEGACY")" +base="$(prompt "BRIDGE_BASE_TOPIC" "$BASE_TOPIC")" + +args=() +[[ -n "$h" ]] && args+=(--set-host "$h") +[[ -n "$u" ]] && args+=(--set-user "$u") +[[ -n "$p" ]] && args+=(--set-pass "$p") +args+=(--set-port "$pr") +args+=(--set-tls "$tls") +args+=(--legacy-itscreen "$leg") +[[ -n "$base" ]] && args+=(--set-base-topic "$base") +args+=(--enable --print) + +exec /usr/local/sbin/iomatex-mqtt-apply "${args[@]}" +__IOMATEX_REMOTE_SET__ +chmod 0755 "$REMOTE_SET" +chown root:root "$REMOTE_SET" + +step "Allow itscreen user to run iomatex-mqtt-apply via sudo (NOPASSWD)" +install -d -m 0755 /etc/sudoers.d +cat >/etc/sudoers.d/90-iomatex-mqtt-apply <<'__IOMATEX_SUDOERS__' +itscreen ALL=(root) NOPASSWD: /usr/local/sbin/iomatex-mqtt-apply +__IOMATEX_SUDOERS__ +chmod 0440 /etc/sudoers.d/90-iomatex-mqtt-apply +if command -v visudo >/dev/null 2>&1; then + visudo -cf /etc/sudoers.d/90-iomatex-mqtt-apply >/dev/null +fi + +step "Create systemd watcher: auto-apply on env changes" +cat >/etc/systemd/system/iomatex-mqtt-bridge.service <<'__IOMATEX_PATH_SVC__' +[Unit] +Description=IOMATEX MQTT Apply (regen mosquitto conf) +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/iomatex-mqtt-apply +__IOMATEX_PATH_SVC__ + +cat >/etc/systemd/system/iomatex-mqtt-bridge.path <<'__IOMATEX_PATH__' +[Unit] +Description=Watch /etc/iomatex/mqtt_bridge.env and re-apply mosquitto config + +[Path] +PathChanged=/etc/iomatex/mqtt_bridge.env +PathModified=/etc/iomatex/mqtt_bridge.env + +[Install] +WantedBy=multi-user.target +__IOMATEX_PATH__ + +step "Create health script" +cat >"$HEALTH_SH" <<'__IOMATEX_HEALTH_SH__' +#!/usr/bin/env bash +set -euo pipefail + +ENV_FILE="/etc/iomatex/mqtt_bridge.env" + +get_kv(){ + local k="$1" line + line="$(grep -m1 -E "^${k}=" "$ENV_FILE" 2>/dev/null || true)" + [[ -n "$line" ]] && echo "${line#${k}=}" || echo "" +} + +if ! systemctl is-active --quiet mosquitto; then + systemctl start mosquitto || systemctl restart mosquitto || true +fi + +h="$(hostname -s 2>/dev/null || hostname)" +BRIDGE_BASE_TOPIC="$(get_kv BRIDGE_BASE_TOPIC)"; : "${BRIDGE_BASE_TOPIC:=v1/edge}" + +ts_main="$(date -u '+%F, %T UTC')" +tz_off="$(date '+%z')" +tz_fmt="(${tz_off:0:3})" +time_str="${ts_main}, time zone ${tz_fmt}" + +payload="{\"status\":\"ok\",\"time\":\"${time_str}\",\"hostname\":\"${h}\"}" +topic="${BRIDGE_BASE_TOPIC}/health/${h}" + +mosquitto_pub -h 127.0.0.1 -p 1883 -t "${topic}" -m "${payload}" >/dev/null 2>&1 || true +__IOMATEX_HEALTH_SH__ +chmod 0755 "$HEALTH_SH" +chown root:root "$HEALTH_SH" + +step "Create health service and timer" +cat >/etc/systemd/system/iomatex-mqtt-health.service <<'__IOMATEX_HEALTH_SVC__' +[Unit] +Description=IOMATEX MQTT health check +After=mosquitto.service +Wants=mosquitto.service + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/iomatex-mqtt-health.sh +__IOMATEX_HEALTH_SVC__ + +cat >/etc/systemd/system/iomatex-mqtt-health.timer <<'__IOMATEX_HEALTH_TIMER__' +[Unit] +Description=Run IOMATEX MQTT health check every minute + +[Timer] +OnBootSec=20s +OnCalendar=*-*-* *:*:00 +AccuracySec=1s +Persistent=true + +[Install] +WantedBy=timers.target +__IOMATEX_HEALTH_TIMER__ + +step "Enable services and apply config now" +systemctl daemon-reload +systemctl enable mosquitto >/dev/null 2>&1 || true +systemctl enable --now iomatex-mqtt-bridge.path +systemctl enable --now iomatex-mqtt-health.timer +/usr/local/sbin/iomatex-mqtt-apply --print || true + +step "Run first health publish immediately" +"$HEALTH_SH" || true + +step "Cleanup temporary debug config (if exists)" +rm -f /etc/mosquitto/conf.d/99-iomatex-debug.conf >/dev/null 2>&1 || true + +step "Print quick status + tips" +BIND="$(awk '($1=="listener" && $2=="1883"){print $3; exit}' /etc/mosquitto/conf.d/01-iomatex-main-listener.conf 2>/dev/null || true)" +echo +echo "Local broker listener (SOURCE OF TRUTH): /etc/mosquitto/conf.d/01-iomatex-main-listener.conf" +echo " listener 1883 ${BIND:-}" +echo +echo "Effective listeners (runtime):" +ss -lntp 2>/dev/null | grep -E ":(1883)\b" || true +echo +echo "ENV: $ENV_FILE" +grep -n -E '^(ENABLE_BRIDGE|REMOTE_HOST|REMOTE_PORT|REMOTE_TLS|REMOTE_USERNAME|REMOTE_CLIENTID|LEGACY_ITSCREEN_TREE|BRIDGE_BASE_TOPIC|REMOTE_PASSWORD)=' "$ENV_FILE" 2>/dev/null | sed -E 's/^(.*REMOTE_PASSWORD=).*/\1/' || true +echo +echo "Bridge conf:" +ls -la /etc/mosquitto/conf.d/50-iomatex-bridge.conf 2>/dev/null || echo " (not present: bridge disabled)" +echo +echo "Bridge topics:" +grep -n -E '^topic ' /etc/mosquitto/conf.d/50-iomatex-bridge.conf 2>/dev/null || true +echo +echo "Expected health topic:" +echo " v1/edge/health/${HOSTNAME_SHORT}" +echo +echo "Actual health topic from env:" +echo " $(grep -m1 '^BRIDGE_BASE_TOPIC=' "$ENV_FILE" 2>/dev/null | cut -d= -f2)/health/${HOSTNAME_SHORT}" +echo +echo "Expected payload example:" +echo " {\"status\":\"ok\",\"time\":\"$(date -u '+%F, %T UTC'), time zone ($(date '+%z' | sed -E 's/^([+-][0-9]{2}).*/\1/'))\",\"hostname\":\"${HOSTNAME_SHORT}\"}" +echo +echo "Manual remote set + report:" +echo " sudo iomatex-mqtt-remote-set" +echo +echo "Non-interactive apply example:" +echo " sudo iomatex-mqtt-apply --set-host dev.it-screen.com --set-user broadcaster --set-pass \"PASS\" --set-port 1883 --set-tls 0 --set-base-topic v1/edge --enable --check --print" +echo +echo "Manual publish test:" +echo " sudo /usr/local/sbin/iomatex-mqtt-health.sh" +echo +echo "Timer check:" +echo " systemctl list-timers --all | grep -F iomatex-mqtt-health" +echo +log "Stage1 MQTT finished successfully." \ No newline at end of file diff --git a/Stage_2_zigbee3mqtt/Database.jason b/Stage_2_zigbee3mqtt/Database.jason new file mode 100755 index 0000000..53cf0cb --- /dev/null +++ b/Stage_2_zigbee3mqtt/Database.jason @@ -0,0 +1,4 @@ +{"id":1,"type":"Coordinator","ieeeAddr":"0xb83dfb6082900000","nwkAddr":0,"manufId":65535,"epList":[1],"endpoints":{"1":{"profId":260,"epId":1,"devId":80,"inClusterList":[0,25],"outClusterList":[0,1,3,4,5,6,8,768,1280,2821,64599],"clusters":{},"binds":[],"configuredReportings":[],"meta":{}}},"interviewCompleted":true,"interviewState":"SUCCESSFUL","meta":{}} +{"id":2,"type":"Router","ieeeAddr":"0x0c4314fffe52ae25","nwkAddr":47345,"manufId":4660,"manufName":"_TZ3000_okaz9tjs","powerSource":"Mains (single phase)","modelId":"TS011F","epList":[1],"endpoints":{"1":{"profId":260,"epId":1,"devId":81,"inClusterList":[0,6,3,4,5,57345,2820,1794,64529],"outClusterList":[25],"clusters":{"genBasic":{"attributes":{"modelId":"TS011F","manufacturerName":"_TZ3000_okaz9tjs","powerSource":1,"zclVersion":2,"appVersion":100,"stackVersion":1,"hwVersion":2,"dateCode":"20210625","swBuildId":"500+TZSKT31BS103"}},"haElectricalMeasurement":{"attributes":{"acCurrentDivisor":1000,"acCurrentMultiplier":1,"rmsVoltage":231,"rmsCurrent":0,"activePower":0}},"seMetering":{"attributes":{"divisor":100,"multiplier":1,"currentSummDelivered":0}},"genOnOff":{"attributes":{"onOff":1}},"manuSpecificTuya3":{"attributes":{"powerOnBehavior":2,"switchType":2}}},"binds":[],"configuredReportings":[],"meta":{}}},"appVersion":100,"stackVersion":1,"hwVersion":2,"dateCode":"20210625","swBuildId":"500+TZSKT31BS103","zclVersion":2,"interviewCompleted":true,"interviewState":"SUCCESSFUL","meta":{"configured":332242049},"lastSeen":1771907208362} +{"id":3,"type":"EndDevice","ieeeAddr":"0xffffb40e0606b15b","nwkAddr":18225,"manufId":5127,"manufName":"Third Reality, Inc","powerSource":"Battery","modelId":"3RSM0147Z","epList":[1],"endpoints":{"1":{"profId":260,"epId":1,"devId":770,"inClusterList":[0,65281,1,1026,1029,1032],"outClusterList":[25],"clusters":{"genBasic":{"attributes":{"modelId":"3RSM0147Z","manufacturerName":"Third Reality, Inc","powerSource":3,"zclVersion":3,"appVersion":46,"stackVersion":2,"hwVersion":0,"swBuildId":"v1.00.46"}},"msTemperatureMeasurement":{"attributes":{"measuredValue":2725}},"msRelativeHumidity":{"attributes":{"measuredValue":0}},"msSoilMoisture":{"attributes":{"measuredValue":0}},"genPowerCfg":{"attributes":{"batteryVoltage":15,"batteryPercentageRemaining":189}}},"binds":[{"cluster":1026,"type":"endpoint","deviceIeeeAddress":"0xb83dfb6082900000","endpointID":1},{"cluster":1032,"type":"endpoint","deviceIeeeAddress":"0xb83dfb6082900000","endpointID":1},{"cluster":1,"type":"endpoint","deviceIeeeAddress":"0xb83dfb6082900000","endpointID":1}],"configuredReportings":[{"cluster":1026,"attrId":0,"minRepIntval":10,"maxRepIntval":3600,"repChange":100},{"cluster":1032,"attrId":0,"minRepIntval":10,"maxRepIntval":3600,"repChange":100},{"cluster":1,"attrId":33,"minRepIntval":3600,"maxRepIntval":65000,"repChange":10}],"meta":{}}},"appVersion":46,"stackVersion":2,"hwVersion":0,"swBuildId":"v1.00.46","zclVersion":3,"interviewCompleted":true,"interviewState":"SUCCESSFUL","meta":{"configured":332242049},"lastSeen":1771907081855} +{"id":4,"type":"EndDevice","ieeeAddr":"0xffffb40e0606b17f","nwkAddr":41920,"manufId":5127,"manufName":"Third Reality, Inc","powerSource":"Battery","modelId":"3RSM0147Z","epList":[1],"endpoints":{"1":{"profId":260,"epId":1,"devId":770,"inClusterList":[0,65281,1,1026,1029,1032],"outClusterList":[25],"clusters":{"msTemperatureMeasurement":{"attributes":{"measuredValue":2734}},"msRelativeHumidity":{"attributes":{"measuredValue":0}},"msSoilMoisture":{"attributes":{"measuredValue":0}},"genBasic":{"attributes":{"modelId":"3RSM0147Z","manufacturerName":"Third Reality, Inc","powerSource":3,"zclVersion":3,"appVersion":46,"stackVersion":2,"hwVersion":0,"swBuildId":"v1.00.46"}},"genPowerCfg":{"attributes":{"batteryVoltage":15,"batteryPercentageRemaining":193}}},"binds":[{"cluster":1026,"type":"endpoint","deviceIeeeAddress":"0xb83dfb6082900000","endpointID":1},{"cluster":1032,"type":"endpoint","deviceIeeeAddress":"0xb83dfb6082900000","endpointID":1},{"cluster":1,"type":"endpoint","deviceIeeeAddress":"0xb83dfb6082900000","endpointID":1}],"configuredReportings":[{"cluster":1026,"attrId":0,"minRepIntval":10,"maxRepIntval":3600,"repChange":100},{"cluster":1032,"attrId":0,"minRepIntval":10,"maxRepIntval":3600,"repChange":100},{"cluster":1,"attrId":33,"minRepIntval":3600,"maxRepIntval":65000,"repChange":10}],"meta":{}}},"appVersion":46,"stackVersion":2,"hwVersion":0,"swBuildId":"v1.00.46","zclVersion":3,"interviewCompleted":true,"interviewState":"SUCCESSFUL","meta":{"configured":332242049},"lastSeen":1771907094193} \ No newline at end of file diff --git a/Stage_2_zigbee3mqtt/Help.md b/Stage_2_zigbee3mqtt/Help.md new file mode 100755 index 0000000..25ac1e5 --- /dev/null +++ b/Stage_2_zigbee3mqtt/Help.md @@ -0,0 +1,103 @@ +# Zigbee2MQTT Installer — What This Script Does + +## Общая задача +Автоматически устанавливает и настраивает **Zigbee2MQTT** на edge-устройстве IOMATEX в полностью **non-interactive** режиме, готовом для работы инженерами «из коробки». + +--- + +## Последовательность действий скрипта + +1. **Проверяет запуск от root** + - Завершает работу с ошибкой, если запущен не через `sudo`. + +2. **Инициализирует логирование** + - Создаёт файл лога установки. + - Перенаправляет `stdout` и `stderr` в лог и консоль. + +3. **Выводит информацию о версии установки** + - Версия installer’а. + - Текущее UTC-время. + +4. **Объявляет вспомогательные функции** + - `spinner()` — визуальный индикатор выполнения долгих операций. + - `run_bg()` — запуск команд в фоне со spinner’ом и корректной обработкой ошибок. + +5. **Устанавливает системные зависимости** + - Базовые пакеты (curl, git, build-tools, udev, usbutils и т.д.). + +6. **Устанавливает Node.js** + - Устанавливает Node.js заданной major-версии (через NodeSource). + - Проверяет версии `node` и `npm`. + +7. **Включает Corepack** + - Активирует Corepack. + - Обеспечивает полностью non-interactive загрузку `pnpm`. + +8. **Создаёт системного пользователя Zigbee2MQTT** + - Пользователь `zigbee2mqtt` без shell. + - Добавляет пользователя в группу `dialout` для доступа к USB-устройствам. + +9. **Клонирует репозиторий Zigbee2MQTT** + - Загружает официальный репозиторий в `/opt/zigbee2mqtt`. + +10. **Готовит директорию данных** + - Создаёт `/opt/zigbee2mqtt/data`. + - Назначает владельца и права доступа. + - (Опционально) разрешает чтение конфигурации инженеру. + +11. **Обнаруживает Zigbee USB-dongle** + - Ожидает появления устройства через udev. + - Ищет dongle в следующем порядке: + - фиксированный путь `/dev/serial/by-id/...` + - любой `/dev/serial/by-id/*` + - fallback: `/dev/ttyUSB*` или `/dev/ttyACM*` + - Если dongle не найден — установка продолжается с предупреждением. + +12. **Генерирует `configuration.yaml`** + - MQTT-настройки. + - Serial-порт и тип адаптера. + - Включает Web UI на `0.0.0.0:8081` (HTTP). + - Генерирует `network_key`. + +13. **Устанавливает и собирает Zigbee2MQTT** + - Выполняет `pnpm install`. + - Выполняет `pnpm run build`. + - Все операции выполняются non-interactive со spinner’ом. + +14. **Создаёт systemd-сервис** + - Конфигурирует сервис `zigbee2mqtt`. + - Прямой запуск через `node index.js`. + - Включает автозапуск при старте системы. + +15. **Устанавливает helper-команду** + - Команда `iomatex-z2m` для инженеров. + - Показывает: + - IP устройства. + - ссылку на Web UI. + - статус сервиса. + - состояние USB и serial-портов. + - последние ошибки. + +16. **(Опционально) Подготавливает Warning для Cockpit** + - Генерирует файл в `/etc/motd.d/` с предупреждением о состоянии dongle. + - По умолчанию отключено флагом. + +17. **Запускает сервис и выполняет быстрый self-check** + - Проверяет, активен ли сервис. + - Проверяет, слушается ли Web-порт. + +18. **Выводит финальное резюме установки** + - Web UI URL. + - MQTT-сервер и topic. + - Serial-порт. + - Тип адаптера. + - Команды для диагностики. + +--- + +## Результат +После выполнения скрипта: +- Zigbee2MQTT установлен и готов к работе. +- Web UI доступен по HTTP на порту 8081. +- Установка не требует ручных подтверждений. +- Инженер получает понятную диагностику и инструменты поддержки. diff --git a/Stage_2_zigbee3mqtt/configuration.yaml b/Stage_2_zigbee3mqtt/configuration.yaml new file mode 100755 index 0000000..1950258 --- /dev/null +++ b/Stage_2_zigbee3mqtt/configuration.yaml @@ -0,0 +1,40 @@ +enabled: false +mqtt: + server: mqtt://uae.iomatex.com:1883 + user: broadcaster + password: Y6gDoqbayn36ozn3a + base_topic: zigbee2mqtt/g-box-8514 +device_options: + legacy: false +availability: + enabled: true +serial: + port: /dev/serial/by-id/usb-1a86_USB_Serial-if00-port0 + adapter: zigate +frontend: + enabled: true + port: 8081 + host: 0.0.0.0 +advanced: + log_level: info + cache_state: true + cache_state_persistent: true + cache_state_send_on_startup: true + network_key: + - 8 + - 94 + - 167 + - 174 + - 199 + - 184 + - 213 + - 106 + - 196 + - 250 + - 112 + - 149 + - 97 + - 173 + - 1 + - 172 +version: 5 \ No newline at end of file diff --git a/Stage_2_zigbee3mqtt/stage2.sh b/Stage_2_zigbee3mqtt/stage2.sh new file mode 100755 index 0000000..99cb8a9 --- /dev/null +++ b/Stage_2_zigbee3mqtt/stage2.sh @@ -0,0 +1,464 @@ +#!/usr/bin/env bash +set -euo pipefail + +LOG="/var/log/iomatex-stage2-z2m.log" +mkdir -p "$(dirname "$LOG")" >/dev/null 2>&1 || true +exec > >(tee -a "$LOG") 2>&1 + +# Must run as root +if [ "${EUID:-$(id -u)}" -ne 0 ]; then + echo "Run as root: sudo $0" + exit 1 +fi + +echo "=== IOMATEX stage2.sh :: Zigbee2MQTT install/upgrade (NO DATA WIPE) v3 (hostname topic) ===" +date -u +"UTC: %Y-%m-%d %H:%M:%S" + +# ---------------- SETTINGS ---------------- +Z2M_USER="zigbee2mqtt" +Z2M_DIR="/opt/zigbee2mqtt" +Z2M_DATA_DIR="/opt/zigbee2mqtt/data" +CFG="${Z2M_DATA_DIR}/configuration.yaml" + +NODE_MAJOR="20" + +# Policy: LOCAL MQTT ONLY +MQTT_SERVER="mqtt://127.0.0.1:1883" +HOSTNAME_SHORT="$(hostname -s)" +MQTT_BASE_TOPIC="${HOSTNAME_SHORT}/z2m" + +WEB_PORT_DEFAULT="8081" + +# Preferred stable path (if present) +SERIAL_BY_ID="/dev/serial/by-id/usb-1a86_USB_Serial-if00-port0" +Z2M_ADAPTER="zigate" + +DONGLE_WAIT_SECONDS=20 +ALLOW_READ_USER="iomatex" # "" to skip + +# Wrapper behavior (no-dongle polling) +NO_DONGLE_SLEEP=300 # seconds (5 minutes) +CRASH_SLEEP_MIN=10 +CRASH_SLEEP_MAX=120 +# ----------------------------------------- + +spinner() { + local pid="$1" + local msg="${2:-Working}" + local spin='|/-\\' + local i=0 + command -v tput >/dev/null 2>&1 && tput civis || true + while kill -0 "$pid" 2>/dev/null; do + i=$(( (i+1) % 4 )) + printf "\r%s %s" "${spin:$i:1}" "$msg" + sleep 0.15 + done + printf "\r✓ %s\n" "$msg" + command -v tput >/dev/null 2>&1 && tput cnorm || true +} + +run_bg() { + local msg="$1"; shift + set +e + ("$@") & + local pid=$! + spinner "$pid" "$msg" + wait "$pid" + local rc=$? + set -e + return "$rc" +} + +echo "=== APT baseline ===" +apt-get update +apt-get install -y --no-install-recommends \ + ca-certificates curl gnupg git jq sudo nano \ + build-essential python3 make g++ \ + usbutils udev dos2unix + +echo "=== Install Node.js ${NODE_MAJOR}.x (NodeSource) if needed ===" +if ! command -v node >/dev/null 2>&1 || ! node -v | grep -qE "^v${NODE_MAJOR}\."; then + install -m 0755 -d /etc/apt/keyrings + curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key \ + | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg + echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_${NODE_MAJOR}.x nodistro main" \ + > /etc/apt/sources.list.d/nodesource.list + apt-get update + apt-get install -y nodejs +fi +node -v +npm -v + +echo "=== Enable pnpm via corepack (non-interactive) ===" +export COREPACK_ENABLE_DOWNLOAD_PROMPT=0 +corepack enable || true +pnpm -v || true + +echo "=== Ensure user ${Z2M_USER} ===" +if ! id -u "$Z2M_USER" >/dev/null 2>&1; then + useradd -r -m -d "/home/${Z2M_USER}" -s /usr/sbin/nologin "$Z2M_USER" +fi +usermod -aG dialout "$Z2M_USER" || true + +echo "=== Ensure data dir exists (DO NOT WIPE) ===" +mkdir -p "$Z2M_DATA_DIR" +chown -R "$Z2M_USER:$Z2M_USER" "$Z2M_DATA_DIR" +chmod 750 "$Z2M_DATA_DIR" + +if [ -n "$ALLOW_READ_USER" ] && id -u "$ALLOW_READ_USER" >/dev/null 2>&1; then + chgrp -R "$ALLOW_READ_USER" "$Z2M_DATA_DIR" || true + chmod -R g+rX "$Z2M_DATA_DIR" || true +fi + +echo "=== Install/Update Zigbee2MQTT code (keep data) ===" +if [ -d "${Z2M_DIR}/.git" ]; then + cd "$Z2M_DIR" + git remote set-url origin https://github.com/Koenkk/zigbee2mqtt.git + git fetch --depth 1 origin + git reset --hard origin/master +else + rm -rf "$Z2M_DIR" + git clone --depth 1 https://github.com/Koenkk/zigbee2mqtt.git "$Z2M_DIR" +fi +chown -R "$Z2M_USER:$Z2M_USER" "$Z2M_DIR" + +echo "=== Detect serial dongle (best effort) ===" +detect_serial() { + local found="" + if [ -e "$SERIAL_BY_ID" ]; then + echo "$SERIAL_BY_ID"; return 0 + fi + if [ -d /dev/serial/by-id ] && ls -1 /dev/serial/by-id/* >/dev/null 2>&1; then + found="$(ls -1 /dev/serial/by-id/* 2>/dev/null | head -n1 || true)" + [ -n "$found" ] && echo "$found" && return 0 + fi + found="$(ls -1 /dev/ttyUSB* /dev/ttyACM* 2>/dev/null | head -n1 || true)" + [ -n "$found" ] && echo "$found" && return 0 + return 1 +} + +DETECTED_SERIAL="" +for _i in $(seq 1 "$DONGLE_WAIT_SECONDS"); do + if DETECTED_SERIAL="$(detect_serial 2>/dev/null)"; then break; fi + sleep 1 +done +DETECTED_SERIAL="${DETECTED_SERIAL:-$SERIAL_BY_ID}" +echo "Serial candidate: ${DETECTED_SERIAL}" +echo "MQTT base_topic: ${MQTT_BASE_TOPIC}" + +echo "=== configuration.yaml handling ===" +if [ ! -f "$CFG" ]; then + echo "No config found -> creating new config at: $CFG" + cat > "$CFG" <<__Z2M_CFG_NEW__ +homeassistant: + enabled: false + +mqtt: + server: ${MQTT_SERVER} + base_topic: ${MQTT_BASE_TOPIC} + +serial: + port: ${DETECTED_SERIAL} + adapter: ${Z2M_ADAPTER} + +frontend: + enabled: true + port: ${WEB_PORT_DEFAULT} + host: 0.0.0.0 + +advanced: + log_level: info +__Z2M_CFG_NEW__ + chown "$Z2M_USER:$Z2M_USER" "$CFG" + chmod 640 "$CFG" +else + echo "Config exists -> will NOT overwrite. Will patch mqtt.server/base_topic and remove mqtt auth if present." + + # Remove mqtt auth lines if exist (user/password/username) + sed -i -E '/^[[:space:]]*(user|username|password)[[:space:]]*:/d' "$CFG" + + # Ensure mqtt section exists; if not, append minimal mqtt block. + if ! grep -qE '^[[:space:]]*mqtt:[[:space:]]*$' "$CFG"; then + cat >> "$CFG" <<__Z2M_MQTT_BLOCK__ + +mqtt: + server: ${MQTT_SERVER} + base_topic: ${MQTT_BASE_TOPIC} +__Z2M_MQTT_BLOCK__ + fi + + # Patch mqtt.server + if grep -qE '^[[:space:]]*server:[[:space:]]*' "$CFG"; then + awk -v new=" server: ${MQTT_SERVER}" ' + BEGIN{in=0;done=0} + /^[[:space:]]*mqtt:[[:space:]]*$/ {in=1} + in && !done && /^[[:space:]]*server:[[:space:]]*/ {print new; done=1; next} + /^[[:alpha:]_]+:/ && $0 !~ /^mqtt:/ {in=0} + {print} + ' "$CFG" > "${CFG}.tmp" && mv "${CFG}.tmp" "$CFG" + else + awk -v s=" server: ${MQTT_SERVER}" ' + BEGIN{in=0;ins=0} + /^[[:space:]]*mqtt:[[:space:]]*$/ {in=1; print; next} + in && !ins && /^[[:space:]]*[a-zA-Z_]+:/ {print s; ins=1; in=0} + {print} + END{ if(in && !ins){print s} } + ' "$CFG" > "${CFG}.tmp" && mv "${CFG}.tmp" "$CFG" + fi + + # Patch mqtt.base_topic + if grep -qE '^[[:space:]]*base_topic:[[:space:]]*' "$CFG"; then + awk -v new=" base_topic: ${MQTT_BASE_TOPIC}" ' + BEGIN{in=0;done=0} + /^[[:space:]]*mqtt:[[:space:]]*$/ {in=1} + in && !done && /^[[:space:]]*base_topic:[[:space:]]*/ {print new; done=1; next} + /^[[:alpha:]_]+:/ && $0 !~ /^mqtt:/ {in=0} + {print} + ' "$CFG" > "${CFG}.tmp" && mv "${CFG}.tmp" "$CFG" + else + awk -v b=" base_topic: ${MQTT_BASE_TOPIC}" ' + BEGIN{in=0;ins=0} + /^[[:space:]]*mqtt:[[:space:]]*$/ {in=1; print; next} + in && !ins && /^[[:space:]]*[a-zA-Z_]+:/ {print b; ins=1; in=0} + {print} + END{ if(in && !ins){print b} } + ' "$CFG" > "${CFG}.tmp" && mv "${CFG}.tmp" "$CFG" + fi + + chown "$Z2M_USER:$Z2M_USER" "$CFG" || true + chmod 640 "$CFG" || true +fi + +echo "=== pnpm install + build (non-interactive) ===" +cd "$Z2M_DIR" +sudo -u "$Z2M_USER" env COREPACK_ENABLE_DOWNLOAD_PROMPT=0 pnpm config set fetch-timeout 600000 >/dev/null +sudo -u "$Z2M_USER" env COREPACK_ENABLE_DOWNLOAD_PROMPT=0 pnpm config set fetch-retries 10 >/dev/null +run_bg "pnpm install" sudo -u "$Z2M_USER" env COREPACK_ENABLE_DOWNLOAD_PROMPT=0 pnpm install +run_bg "pnpm build" sudo -u "$Z2M_USER" env COREPACK_ENABLE_DOWNLOAD_PROMPT=0 pnpm run build + +echo "=== Dongle-aware wrapper (prevents restart storm when stick is missing) ===" +cat > /usr/local/sbin/iomatex-z2m-wrapper.sh <<__Z2M_WRAPPER__ +#!/usr/bin/env bash +set -euo pipefail + +Z2M_DIR="${Z2M_DIR}" +CFG="${CFG}" +SERIAL_BY_ID="${SERIAL_BY_ID}" + +NO_DONGLE_SLEEP=${NO_DONGLE_SLEEP} +CRASH_SLEEP_MIN=${CRASH_SLEEP_MIN} +CRASH_SLEEP_MAX=${CRASH_SLEEP_MAX} + +log(){ echo "[\$(date -u +'%F %T UTC')] \$*"; } + +detect_serial() { + local found="" + if [ -e "\$SERIAL_BY_ID" ]; then + echo "\$SERIAL_BY_ID"; return 0 + fi + if [ -d /dev/serial/by-id ] && ls -1 /dev/serial/by-id/* >/dev/null 2>&1; then + found="\$(ls -1 /dev/serial/by-id/* 2>/dev/null | head -n1 || true)" + [ -n "\$found" ] && echo "\$found" && return 0 + fi + found="\$(ls -1 /dev/ttyUSB* /dev/ttyACM* 2>/dev/null | head -n1 || true)" + [ -n "\$found" ] && echo "\$found" && return 0 + return 1 +} + +patch_cfg_port_if_needed() { + local port="\$1" + [ -f "\$CFG" ] || return 0 + awk -v new=" port: \${port}" ' + BEGIN{in=0;done=0} + /^[[:space:]]*serial:[[:space:]]*$/ {in=1} + in && !done && /^[[:space:]]*port:[[:space:]]*/ {print new; done=1; next} + /^[[:alpha:]_]+:/ && \$0 !~ /^serial:/ {in=0} + {print} + ' "\$CFG" > "\${CFG}.tmp" && mv "\${CFG}.tmp" "\$CFG" +} + +crash_sleep="\$CRASH_SLEEP_MIN" +log "IOMATEX Zigbee2MQTT wrapper started" + +while true; do + if serial="\$(detect_serial 2>/dev/null)"; then + log "Dongle detected: \${serial}" + patch_cfg_port_if_needed "\$serial" || true + + log "Starting Zigbee2MQTT..." + set +e + /usr/bin/node "\${Z2M_DIR}/index.js" + rc=\$? + set -e + log "Zigbee2MQTT exited with rc=\${rc}" + + if ! detect_serial >/dev/null 2>&1; then + log "Dongle not present after exit -> sleeping \${NO_DONGLE_SLEEP}s" + crash_sleep="\$CRASH_SLEEP_MIN" + sleep "\$NO_DONGLE_SLEEP" + else + log "Dongle still present -> crash backoff \${crash_sleep}s" + sleep "\$crash_sleep" + crash_sleep=\$(( crash_sleep * 2 )) + [ "\$crash_sleep" -gt "\$CRASH_SLEEP_MAX" ] && crash_sleep="\$CRASH_SLEEP_MAX" + fi + else + log "No dongle detected -> sleeping \${NO_DONGLE_SLEEP}s" + crash_sleep="\$CRASH_SLEEP_MIN" + sleep "\$NO_DONGLE_SLEEP" + fi +done +__Z2M_WRAPPER__ +chmod 0755 /usr/local/sbin/iomatex-z2m-wrapper.sh +chown root:root /usr/local/sbin/iomatex-z2m-wrapper.sh + +echo "=== systemd service (wrapper-based, no restart storm) ===" +cat > /etc/systemd/system/zigbee2mqtt.service <<__Z2M_SVC__ +[Unit] +Description=Zigbee2MQTT (local MQTT only) with dongle-aware wrapper +After=network-online.target mosquitto.service +Wants=network-online.target mosquitto.service + +[Service] +Type=simple +User=${Z2M_USER} +WorkingDirectory=${Z2M_DIR} +Environment=NODE_ENV=production +Environment=ZIGBEE2MQTT_DATA=${Z2M_DATA_DIR} +Environment=PATH=/usr/bin:/bin +ExecStart=/usr/local/sbin/iomatex-z2m-wrapper.sh + +Restart=on-failure +RestartSec=30 +StartLimitIntervalSec=0 +LimitNOFILE=65536 + +[Install] +WantedBy=multi-user.target +__Z2M_SVC__ + +echo "=== Healthcheck timer (skip when no dongle, run every 5 min) ===" +cat > /usr/local/sbin/iomatex-z2m-healthcheck.sh <<__Z2M_HC_SH__ +#!/usr/bin/env bash +set -euo pipefail +SVC="zigbee2mqtt" +STAMP="/var/log/iomatex-z2m-healthcheck.log" +SERIAL_BY_ID="${SERIAL_BY_ID}" + +log(){ echo "[\$(date -u +'%F %T UTC')] \$*" >> "\$STAMP"; } + +have_dongle() { + [ -e "\$SERIAL_BY_ID" ] && return 0 + ls -1 /dev/serial/by-id/* >/dev/null 2>&1 && return 0 + ls -1 /dev/ttyUSB* /dev/ttyACM* >/dev/null 2>&1 && return 0 + return 1 +} + +if ! have_dongle; then + log "No dongle -> skip" + exit 0 +fi + +if systemctl is-active --quiet "\$SVC"; then + exit 0 +fi + +log "Service NOT active (dongle present) -> restart" +systemctl restart "\$SVC" || true +sleep 2 + +if systemctl is-active --quiet "\$SVC"; then + log "Restart OK" +else + log "Restart FAILED" +fi +__Z2M_HC_SH__ +chmod 0755 /usr/local/sbin/iomatex-z2m-healthcheck.sh + +cat > /etc/systemd/system/iomatex-z2m-healthcheck.service <<'__Z2M_HC_SVC__' +[Unit] +Description=IOMATEX Zigbee2MQTT healthcheck (restart if down and dongle present) + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/iomatex-z2m-healthcheck.sh +__Z2M_HC_SVC__ + +cat > /etc/systemd/system/iomatex-z2m-healthcheck.timer <<'__Z2M_HC_TIMER__' +[Unit] +Description=Run IOMATEX Zigbee2MQTT healthcheck every 5 minutes + +[Timer] +OnBootSec=90 +OnUnitActiveSec=300 +AccuracySec=30 +Persistent=true + +[Install] +WantedBy=timers.target +__Z2M_HC_TIMER__ + +echo "=== Help command: iomatex-help-z2m ===" +cat > /usr/local/bin/iomatex-help-z2m <<'__Z2M_HELP__' +#!/usr/bin/env bash +set -euo pipefail +SERVICE="zigbee2mqtt" +CFG="/opt/zigbee2mqtt/data/configuration.yaml" +WRAP="/usr/local/sbin/iomatex-z2m-wrapper.sh" + +hr(){ echo "------------------------------------------------------------"; } +h(){ echo -e "\n\033[1m$1\033[0m"; } + +IP="$(hostname -I | awk '{print $1}')" +HN="$(hostname -s)" +WEB_PORT="$(awk '/^frontend:/{f=1} f&&/port:/{print $2; exit}' "$CFG" 2>/dev/null || echo "8081")" +MQTT_SERVER="$(awk '/^mqtt:/{f=1} f&&/server:/{print $2; exit}' "$CFG" 2>/dev/null || echo "mqtt://127.0.0.1:1883")" +BASE_TOPIC="$(awk '/^mqtt:/{f=1} f&&/base_topic:/{print $2; exit}' "$CFG" 2>/dev/null || echo "${HN}/z2m")" +SERIAL_PORT="$(awk '/^serial:/{f=1} f&&/port:/{print $2; exit}' "$CFG" 2>/dev/null || echo "")" +ADAPTER="$(awk '/^serial:/{f=1} f&&/adapter:/{print $2; exit}' "$CFG" 2>/dev/null || echo "")" + +h "IOMATEX Zigbee2MQTT help/status" +hr +echo "Host : $(hostname)" +echo "IP : ${IP}" +echo "Config : ${CFG}" +echo "Wrapper : ${WRAP}" +echo "Web UI : http://${IP}:${WEB_PORT}" +echo "MQTT : ${MQTT_SERVER}" +echo "Base topic: ${BASE_TOPIC}" +echo "Serial : ${SERIAL_PORT}" +echo "Adapter : ${ADAPTER}" +hr + +h "Service status" +systemctl status "${SERVICE}" --no-pager -l || true + +h "Healthcheck timer" +systemctl status iomatex-z2m-healthcheck.timer --no-pager -l || true +tail -n 60 /var/log/iomatex-z2m-healthcheck.log 2>/dev/null || true + +h "Recent errors/warnings" +journalctl -u "${SERVICE}" -n 200 --no-pager | grep -i -E "error|fail|fatal|adapter|usb|mqtt|zigate|serial" || echo "No recent errors/warnings" + +h "USB/Serial" +lsusb || true +ls -l /dev/serial/by-id/ 2>/dev/null || echo "No /dev/serial/by-id" +ls -l /dev/ttyUSB* /dev/ttyACM* 2>/dev/null || true +__Z2M_HELP__ +chmod +x /usr/local/bin/iomatex-help-z2m +ln -sf /usr/local/bin/iomatex-help-z2m /usr/local/bin/iomatex-z2m + +echo "=== Enable & start services ===" +systemctl daemon-reload +systemctl enable zigbee2mqtt >/dev/null 2>&1 || true +systemctl enable iomatex-z2m-healthcheck.timer >/dev/null 2>&1 || true +systemctl restart zigbee2mqtt || systemctl start zigbee2mqtt +systemctl start iomatex-z2m-healthcheck.timer || true + +echo "=== Done ===" +echo "Data kept : ${Z2M_DATA_DIR}" +echo "Config kept : ${CFG}" +echo "MQTT base_topic: ${MQTT_BASE_TOPIC}" +echo "Help : iomatex-help-z2m (or iomatex-z2m)" +echo "Logs : journalctl -u zigbee2mqtt -f" +echo "NOTE: Without dongle, wrapper sleeps ${NO_DONGLE_SLEEP}s between checks." \ No newline at end of file diff --git a/Stage_3 (Itscreen_app)/IOMATEX_stage_1.md b/Stage_3 (Itscreen_app)/IOMATEX_stage_1.md new file mode 100755 index 0000000..e099cb4 --- /dev/null +++ b/Stage_3 (Itscreen_app)/IOMATEX_stage_1.md @@ -0,0 +1,66 @@ +# IOMATEX Desktop Toggle --- Engineer Cheat Sheet + +## Purpose + +Switch device between **production kiosk (EGLFS)** and **engineer +desktop (X11)** modes. + +------------------------------------------------------------------------ + +## iomatex-desktop-off --- Production mode (EGLFS) + +Actions: 1. Stops engineer services: - itscreen-x11 - lightdm 2. Resets +EGLFS failures 3. Starts: - itscreen-eglfs + +Result: - Kiosk mode - Minimal resource usage - Autostarts after reboot + +------------------------------------------------------------------------ + +## iomatex-desktop-on --- Engineer mode (X11) + +Actions: 1. Stops production kiosk: - itscreen-eglfs 2. Starts +desktop: - lightdm 3. Waits for X display :0 4. Starts: - itscreen-x11 +(runs as user iomatex) + +Result: - Desktop environment available - Chromium and tools usable - +itscreen runs via X11 + +------------------------------------------------------------------------ + +## Key architecture rules + +- Single runtime user: iomatex +- Shared registration: /var/lib/itscreen +- No dual app launches +- Default after reboot: EGLFS production mode + +------------------------------------------------------------------------ + +## Engineer commands + +Switch modes: + + iomatex-desktop-on + iomatex-desktop-off + +Check services: + + systemctl status itscreen-eglfs + systemctl status itscreen-x11 + +Logs: + + journalctl -u itscreen-eglfs -n 100 + journalctl -u itscreen-x11 -n 100 + +------------------------------------------------------------------------ + +## System meaning + +This is a runtime UI mode switch: + +- DRM/EGLFS → kiosk OS +- X11 → engineer workstation + +Controls: - display stack - systemd services - Qt runtime environment - +WebView execution mode diff --git a/Stage_3 (Itscreen_app)/old_stage3.sh (x11+eglfs) b/Stage_3 (Itscreen_app)/old_stage3.sh (x11+eglfs) new file mode 100755 index 0000000..c1f0169 --- /dev/null +++ b/Stage_3 (Itscreen_app)/old_stage3.sh (x11+eglfs) @@ -0,0 +1,293 @@ +#!/usr/bin/env bash +set -euo pipefail +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +export DEBIAN_FRONTEND=noninteractive + +LOG="/var/log/iomatex-stage1-itscreen.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 +} + +step_n=0 +step() { step_n=$((step_n+1)); echo; echo "=== Step ${step_n}: $* ==="; log "STEP ${step_n}: $*"; } + +spinner() { + local pid="$1" + local msg="${2:-Working}" + local spin='|/-\' + local i=0 + command -v tput >/dev/null 2>&1 && tput civis || true + while kill -0 "$pid" 2>/dev/null; do + i=$(( (i+1) % 4 )) + printf "\r[%c] %s..." "${spin:$i:1}" "$msg" + sleep 0.2 + done + printf "\r[✓] %s. \n" "$msg" + command -v tput >/dev/null 2>&1 && tput cnorm || true +} + +run_long() { + local msg="$1"; shift + local timeout_s="$1"; shift + log "RUN: $msg :: $*" + ( timeout "$timeout_s" "$@" >>"$LOG" 2>&1 ) & + local pid=$! + spinner "$pid" "$msg" + wait "$pid" +} + +soft_run() { + local msg="$1"; shift + local timeout_s="$1"; shift + if run_long "$msg" "$timeout_s" "$@"; then return 0; else return 0; fi +} + +# root +if [ "${EUID:-$(id -u)}" -ne 0 ]; then exec sudo -E /bin/bash "$0" "$@"; fi + +log "=== IOMATEX STAGE_3 ITSCREEN (EGLFS or TRUE-HEADLESS) START ===" + +step "Preflight" +run_long "APT update" 900 apt-get update +soft_run "Ensure base packages" 600 apt-get install -y procps util-linux x11-xserver-utils sudo + +id itscreen >/dev/null || { echo "Run Stage_0 first"; exit 2; } + +# shared runtime dirs +install -d -m 0770 -o itscreen -g itscreen /var/lib/itscreen/{config,data,logs} +install -d -m 0755 -o itscreen -g itscreen /var/log/itscreen + +# ------------------------- +step "Install Qt runtime (exact list)" +run_long "Install Qt runtime" 1800 apt-get install -y \ + libqt5webview5 \ + libqt5websockets5 \ + libqt5texttospeech5 \ + libqt5serialbus5 + +soft_run "Install Qt extras" 1800 apt-get install -y \ + gedit lxterminal clang qtcreator \ + libqt5serialbus5-bin \ + qtpositioning5-dev qml-module-qtpositioning \ + libqt5texttospeech5-dev \ + qml-module-qtquick-virtualkeyboard qtvirtualkeyboard-plugin \ + libqt5webview5-dev qml-module-qtwebview \ + qml-module-qt-labs-settings qml-module-qtquick-xmllistmodel \ + libqt5serialbus5-dev \ + qml-module-qtquick-controls2 \ + qml-module-qt-websockets libqt5websockets5-dev \ + qml-module-qt-labs-platform + +ldconfig + +# ------------------------- +step "Install itscreen binary" +if [ -f ./itscreen ]; then SRC=./itscreen; +elif [ -f /home/iomatex/Downloads/itscreen ]; then SRC=/home/iomatex/Downloads/itscreen; +else echo "Binary not found"; exit 2; fi + +install -m0755 "$SRC" /opt/itscreen/bin/itscreen +chown itscreen:itscreen /opt/itscreen/bin/itscreen + +# ------------------------- +step "Grant power actions (reboot/shutdown) to itscreen (sudoers)" +cat >/etc/sudoers.d/90-itscreen-power <<'EOF' +Defaults:itscreen !requiretty +itscreen ALL=(root) NOPASSWD: /sbin/reboot, /usr/sbin/reboot, /bin/systemctl reboot, /usr/bin/systemctl reboot +itscreen ALL=(root) NOPASSWD: /sbin/poweroff, /usr/sbin/poweroff, /bin/systemctl poweroff, /usr/bin/systemctl poweroff +itscreen ALL=(root) NOPASSWD: /sbin/shutdown, /usr/sbin/shutdown, /bin/systemctl halt, /usr/bin/systemctl halt +EOF +chmod 0440 /etc/sudoers.d/90-itscreen-power +visudo -cf /etc/sudoers.d/90-itscreen-power >/dev/null + +# ------------------------- +step "X11 access for itscreen (xhost)" +cat >/etc/X11/Xsession.d/99-iomatex-allow-itscreen <<'EOF' +#!/bin/sh +DISPLAY=${DISPLAY:-:0} xhost +SI:localuser:itscreen >/dev/null 2>&1 || true +EOF +chmod +x /etc/X11/Xsession.d/99-iomatex-allow-itscreen + +# ------------------------- +step "Wrapper with flock" +cat >/usr/local/bin/itscreen-run <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +LOCK="/run/itscreen/itscreen.lock" +export XDG_CONFIG_HOME=/var/lib/itscreen/config +export XDG_DATA_HOME=/var/lib/itscreen/data +export ITSCREEN_LOG_DIR=/var/lib/itscreen/logs +exec flock -n "$LOCK" /opt/itscreen/bin/itscreen "$@" +EOF +chmod +x /usr/local/bin/itscreen-run + +# ------------------------- +step "Systemd services (EGLFS + TRUE-HEADLESS)" + +cat >/etc/systemd/system/itscreen-eglfs.service <<'EOF' +[Unit] +Description=ITSCREEN EGLFS +Wants=network-online.target +After=NetworkManager.service network-online.target systemd-user-sessions.service +Conflicts=itscreen-headless.service itscreen-x11.service lightdm.service + +[Service] +User=itscreen +WorkingDirectory=/opt/itscreen +RuntimeDirectory=itscreen +ExecStartPre=-/usr/bin/pkill -u itscreen -x itscreen +ExecStartPre=/usr/bin/nm-online -s -q --timeout=45 +Environment=QT_QPA_PLATFORM=eglfs +ExecStart=/usr/local/bin/itscreen-run +Restart=always +RestartSec=2 + +[Install] +WantedBy=multi-user.target +EOF + +# TRUE headless requires updated client that supports backend-only mode. +# It must NOT initialize QML/OpenGL/WebEngine. It should run on QCoreApplication. +cat >/etc/systemd/system/itscreen-headless.service <<'EOF' +[Unit] +Description=ITSCREEN TRUE Headless (backend-only) +Wants=network-online.target +After=NetworkManager.service network-online.target +Conflicts=itscreen-eglfs.service itscreen-x11.service lightdm.service + +[Service] +User=itscreen +WorkingDirectory=/opt/itscreen +RuntimeDirectory=itscreen +ExecStartPre=-/usr/bin/pkill -u itscreen -x itscreen +ExecStartPre=/usr/bin/nm-online -s -q --timeout=45 +Environment=ITSCREEN_HEADLESS=1 +ExecStart=/usr/local/bin/itscreen-run --headless +Restart=always +RestartSec=2 +StartLimitIntervalSec=300 +StartLimitBurst=3 + +[Install] +WantedBy=multi-user.target +EOF + +cat >/etc/systemd/system/itscreen-x11.service <<'EOF' +[Unit] +Description=ITSCREEN X11 (requires LightDM) +After=lightdm.service +Conflicts=itscreen-eglfs.service itscreen-headless.service + +[Service] +User=itscreen +WorkingDirectory=/opt/itscreen +RuntimeDirectory=itscreen +ExecStartPre=-/usr/bin/pkill -u itscreen -x itscreen +Environment=DISPLAY=:0 +Environment=QT_QPA_PLATFORM=xcb +ExecStart=/usr/local/bin/itscreen-run +Restart=always +RestartSec=2 + +[Install] +WantedBy=multi-user.target +EOF + +systemctl daemon-reload +systemctl enable NetworkManager-wait-online.service || true + +# ------------------------- +step "Boot-mode selector (no hotplug): HDMI -> EGLFS, no HDMI -> TRUE-HEADLESS" + +cat >/usr/local/sbin/iomatex-itscreen-bootmode <<'EOF' +#!/usr/bin/env bash +set -euo pipefail + +has_display=0 +if ls /sys/class/drm/card*-*/status >/dev/null 2>&1; then + if grep -q "^connected$" /sys/class/drm/card*-*/status 2>/dev/null; then + has_display=1 + fi +fi + +systemctl stop itscreen-eglfs.service itscreen-x11.service itscreen-headless.service 2>/dev/null || true + +if [ "$has_display" -eq 1 ]; then + logger -t iomatex-itscreen-bootmode "HDMI connected -> start EGLFS" + systemctl start itscreen-eglfs.service +else + logger -t iomatex-itscreen-bootmode "No HDMI -> start TRUE-HEADLESS" + systemctl start itscreen-headless.service +fi +EOF +chmod +x /usr/local/sbin/iomatex-itscreen-bootmode + +cat >/etc/systemd/system/iomatex-itscreen-bootmode.service <<'EOF' +[Unit] +Description=IOMATEX ITSCREEN boot-mode selector (EGLFS if HDMI else TRUE-HEADLESS) +After=multi-user.target NetworkManager.service +Wants=network-online.target +After=network-online.target + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/iomatex-itscreen-bootmode + +[Install] +WantedBy=multi-user.target +EOF + +systemctl daemon-reload +systemctl enable --now iomatex-itscreen-bootmode.service + +# Avoid double-start on boot: selector decides. +systemctl disable itscreen-eglfs.service itscreen-headless.service itscreen-x11.service 2>/dev/null || true +systemctl disable --now lightdm.service 2>/dev/null || true + +# ------------------------- +step "Toggle scripts (manual)" + +cat >/usr/local/bin/iomatex-desktop-on <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +systemctl stop itscreen-eglfs.service itscreen-headless.service 2>/dev/null || true +systemctl start lightdm.service +sleep 5 +systemctl start itscreen-x11.service +EOF + +cat >/usr/local/bin/iomatex-desktop-off <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +systemctl stop itscreen-x11.service 2>/dev/null || true +systemctl stop lightdm.service 2>/dev/null || true +systemctl start itscreen-eglfs.service +EOF + +cat >/usr/local/bin/iomatex-headless-on <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +systemctl stop itscreen-x11.service itscreen-eglfs.service 2>/dev/null || true +systemctl stop lightdm.service 2>/dev/null || true +systemctl start itscreen-headless.service +EOF + +chmod +x /usr/local/bin/iomatex-desktop-on /usr/local/bin/iomatex-desktop-off /usr/local/bin/iomatex-headless-on + +# Apply boot-mode now (useful after install without reboot) +systemctl start iomatex-itscreen-bootmode.service >/dev/null 2>&1 || true + +echo +echo "Stage_3 ready." +echo "Mode at boot (no hotplug): HDMI -> EGLFS, no HDMI -> TRUE-HEADLESS (requires updated client)." +echo "itscreen can sudo reboot/shutdown (NOPASSWD)." +echo "Manual:" +echo " X11 engineer mode : iomatex-desktop-on" +echo " EGLFS production : iomatex-desktop-off" +echo " Headless backend : iomatex-headless-on" +echo "Logs:" +echo " journalctl -t iomatex-itscreen-bootmode -n 50 --no-pager" diff --git a/Stage_3 (Itscreen_app)/stage3_x11_only.sh b/Stage_3 (Itscreen_app)/stage3_x11_only.sh new file mode 100755 index 0000000..cfa701b --- /dev/null +++ b/Stage_3 (Itscreen_app)/stage3_x11_only.sh @@ -0,0 +1 @@ +Wif-c@th-un-ceep22a \ No newline at end of file diff --git a/Stage_4 (Reverse tunel)/Help_info.txt b/Stage_4 (Reverse tunel)/Help_info.txt new file mode 100755 index 0000000..df5f876 --- /dev/null +++ b/Stage_4 (Reverse tunel)/Help_info.txt @@ -0,0 +1,27 @@ +# Stage4: Reverse Tunnel — памятка инженеру + +1. Определяем `hostname` устройства и используем его как уникальный идентификатор. + +2. Формируем имя пользователя на VPS по правилу: `tunnel_`. + +3. На EDGE создаём (если нет) отдельный SSH-ключ `ed25519` с именем `iomatex-` в `~/.ssh/`. + +4. Проверяем и фиксируем правильные права на `~/.ssh` и ключи. + +5. Устанавливаем `autossh` (если не установлен). + +6. Создаём systemd-сервис `iomatex-remote`, который стартует после поднятия сети. + +7. Настраиваем reverse-проброс портов: + - VPS порт Cockpit → EDGE Cockpit (9090) + - VPS порт Z2M → EDGE Z2M (8081) + +8. Включаем автозапуск сервиса и запускаем его сразу. + +9. Включаем логирование работы туннеля (systemd + файл логов autossh). + +10. Выводим в консоль публичный ключ EDGE. + +11. Выводим готовую команду для VPS: создать пользователя `tunnel_` и установить ключ в `authorized_keys` с ограничениями. + +12. Результат: после перезагрузки EDGE туннель поднимается автоматически и восстанавливается при потере интернета. diff --git a/Stage_4 (Reverse tunel)/Helper для VPS .sh b/Stage_4 (Reverse tunel)/Helper для VPS .sh new file mode 100755 index 0000000..6f776e7 --- /dev/null +++ b/Stage_4 (Reverse tunel)/Helper для VPS .sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +set -euo pipefail + +# iomatex-calc-port +# Usage: iomatex-calc-port +# +# Computes deterministic ports (same logic as Stage4): +# crc = cksum(hostname).field1 +# slot = crc % PORT_SLOTS +# cockpit = PORT_BASE + slot*2 +# z2m = PORT_BASE + slot*2 + 1 +# +# Also prints ready-to-paste commands for: +# - PowerShell (laptop) +# - Linux/macOS (laptop) +# - VPS quick checks (curl) + +HN="${1:-}" +if [[ -z "$HN" ]]; then + echo "Usage: $(basename "$0") " + exit 2 +fi + +# Keep these in sync with Stage4 defaults +PORT_BASE="${PORT_BASE:-20000}" +PORT_SLOTS="${PORT_SLOTS:-4000}" + +# VPS connection (defaults for Protect) +VPS_HOST="${VPS_HOST:-193.42.111.54}" +VPS_PORT="${VPS_PORT:-2200}" +VPS_USER="${VPS_USER:-broadcaster}" + +# Local ports on laptop +LAPTOP_COCKPIT_PORT="${LAPTOP_COCKPIT_PORT:-9090}" +LAPTOP_Z2M_PORT="${LAPTOP_Z2M_PORT:-8081}" + +CRC="$(cksum <<<"$HN" | awk '{print $1}')" +SLOT="$(( CRC % PORT_SLOTS ))" +COCKPIT="$(( PORT_BASE + SLOT*2 ))" +Z2M="$(( PORT_BASE + SLOT*2 + 1 ))" + +echo +echo "Hostname: $HN" +echo "CRC: $CRC" +echo "Cockpit: $COCKPIT" +echo "Z2M: $Z2M" +echo + +echo "VPS checks:" +echo " curl -I http://localhost:$COCKPIT" +echo " curl -I http://localhost:$Z2M" +echo + +echo "Laptop command (PowerShell):" +echo " ssh -N -p $VPS_PORT -o ExitOnForwardFailure=yes -L $LAPTOP_COCKPIT_PORT:127.0.0.1:$COCKPIT -L $LAPTOP_Z2M_PORT:127.0.0.1:$Z2M $VPS_USER@$VPS_HOST" +echo + +echo "Laptop command (Linux/macOS):" +echo " ssh -N -p $VPS_PORT -o ExitOnForwardFailure=yes \\" +echo " -L $LAPTOP_COCKPIT_PORT:127.0.0.1:$COCKPIT \\" +echo " -L $LAPTOP_Z2M_PORT:127.0.0.1:$Z2M \\" +echo " $VPS_USER@$VPS_HOST" +echo + +echo "Open in browser:" +echo " Cockpit: https://localhost:$LAPTOP_COCKPIT_PORT" +echo " Z2M: http://localhost:$LAPTOP_Z2M_PORT" +echo \ No newline at end of file diff --git a/Stage_4 (Reverse tunel)/port.js b/Stage_4 (Reverse tunel)/port.js new file mode 100755 index 0000000..46c3752 --- /dev/null +++ b/Stage_4 (Reverse tunel)/port.js @@ -0,0 +1,118 @@ +// port.js +// Usage: +// node port.js +// +// Output (3 lines, PowerShell-friendly): +// ssh -N -p 22 -L 9090:127.0.0.1: builder@65.109.116.180 # cockpit +// ssh -N -p 22 -L 8081:127.0.0.1: builder@65.109.116.180 # z2m +// ssh -N -p 22 -L 8099:127.0.0.1: builder@65.109.116.180 # webui +// +// Env overrides (optional): +// VPS_USER, VPS_HOST, VPS_PORT +// COCKPIT_LOCAL_PORT (default 9090) +// Z2M_LOCAL_PORT (default 8081) +// WEBUI_LOCAL_PORT (default 8099) +// PORT_BASE (default 20000), PORT_SLOTS (default 4000) +// NO_COMMENTS=1 + +"use strict"; + +const VPS_USER = process.env.VPS_USER || "builder"; +const VPS_HOST = process.env.VPS_HOST || "65.109.116.180"; +const SSH_PORT = parseInt(process.env.VPS_PORT || "22", 10); + +// Correct local ports (match Stage4) +const COCKPIT_LOCAL_PORT = parseInt(process.env.COCKPIT_LOCAL_PORT || "9090", 10); +const Z2M_LOCAL_PORT = parseInt(process.env.Z2M_LOCAL_PORT || "8081", 10); +const WEBUI_LOCAL_PORT = parseInt(process.env.WEBUI_LOCAL_PORT || "8099", 10); + +// Stage4 defaults +const PORT_BASE = parseInt(process.env.PORT_BASE || "20000", 10); +const PORT_SLOTS = parseInt(process.env.PORT_SLOTS || "4000", 10); + +const WITH_COMMENTS = !(process.env.NO_COMMENTS === "1"); + +// POSIX cksum (Debian /usr/bin/cksum): MSB-first CRC-32, poly 0x04C11DB7, fold length, then ones-complement +const CRC_POLY = 0x04C11DB7 >>> 0; + +const CRC_TABLE = (() => { + const t = new Uint32Array(256); + for (let i = 0; i < 256; i++) { + let c = (i << 24) >>> 0; + for (let k = 0; k < 8; k++) { + c = (c & 0x80000000) ? (((c << 1) >>> 0) ^ CRC_POLY) : ((c << 1) >>> 0); + } + t[i] = c >>> 0; + } + return t; +})(); + +function cksumPosixFirstField(strWithNewline) { + const buf = Buffer.from(strWithNewline, "utf8"); + let crc = 0 >>> 0; + + for (let i = 0; i < buf.length; i++) { + const idx = ((crc >>> 24) ^ buf[i]) & 0xff; + crc = (((crc << 8) >>> 0) ^ CRC_TABLE[idx]) >>> 0; + } + + // fold in length bytes (little-endian) + let len = buf.length >>> 0; + while (len !== 0) { + const b = len & 0xff; + const idx = ((crc >>> 24) ^ b) & 0xff; + crc = (((crc << 8) >>> 0) ^ CRC_TABLE[idx]) >>> 0; + len = (len >>> 8) >>> 0; + } + + return (~crc) >>> 0; +} + +function computePorts(deviceId) { + const hn = String(deviceId || "").trim(); + if (!hn) throw new Error("device_Id is required"); + + // EXACT Stage4: cksum <<<"$hn" includes trailing newline + const crc = cksumPosixFirstField(hn + "\n"); + const slot = crc % PORT_SLOTS; + + const cockpitRemote = PORT_BASE + slot * 3 + 0; + const z2mRemote = PORT_BASE + slot * 3 + 1; + const webuiRemote = PORT_BASE + slot * 3 + 2; + + return { + crc, + slot, + cockpit: { local: COCKPIT_LOCAL_PORT, remote: cockpitRemote }, + z2m: { local: Z2M_LOCAL_PORT, remote: z2mRemote }, + webui: { local: WEBUI_LOCAL_PORT, remote: webuiRemote }, + }; +} + +function buildLines(deviceId) { + const p = computePorts(deviceId); + + const items = [ + ["cockpit", p.cockpit.local, p.cockpit.remote], + ["z2m", p.z2m.local, p.z2m.remote], + ["webui", p.webui.local, p.webui.remote], + ]; + + return items.map(([name, localPort, remotePort]) => { + const cmd = `ssh -N -p ${SSH_PORT} -L ${localPort}:127.0.0.1:${remotePort} ${VPS_USER}@${VPS_HOST}`; + return WITH_COMMENTS ? `${cmd} # ${name}` : cmd; + }); +} + +function main() { + const deviceId = process.argv[2]; + if (!deviceId) { + process.stderr.write("Usage: node port.js \n"); + process.exit(2); + } + process.stdout.write(buildLines(deviceId).join("\n") + "\n"); +} + +if (require.main === module) main(); + +module.exports = { buildLines, computePorts, cksumPosixFirstField }; \ No newline at end of file diff --git a/Stage_4 (Reverse tunel)/stage_reverce_tonel.sh b/Stage_4 (Reverse tunel)/stage_reverce_tonel.sh new file mode 100755 index 0000000..5a3f0e1 --- /dev/null +++ b/Stage_4 (Reverse tunel)/stage_reverce_tonel.sh @@ -0,0 +1,217 @@ +#!/usr/bin/env bash +# ============================================================= +# IOMATEX Stage4 — Reverse SSH Tunnels (production) +# - 3 independent tunnels: Cockpit / Zigbee2MQTT / WebUI +# - services ENABLED but NOT started (start after reboot) +# - autossh + systemd restart for resilience +# - ServerAlive keepalive for network/IP changes +# - prints one-line VPS command (user + key + fail2ban allow) +# ============================================================= + +set -euo pipefail +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +export DEBIAN_FRONTEND=noninteractive + +LOG="/var/log/iomatex-stage4-reverse-tunnel-install.log" +mkdir -p /var/log >/dev/null 2>&1 || true +touch "$LOG" >/dev/null 2>&1 || true +exec > >(tee -a "$LOG") 2>&1 + +log(){ echo "[$(date -u +'%F %T UTC')] $*"; } + +need_root(){ + if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then + echo "Run as root: sudo bash $0" + exit 1 + fi +} + +EDGE_USER="${EDGE_USER:-iomatex}" + +VPS_HOST="${VPS_HOST:-65.109.116.180}" +VPS_PORT="${VPS_PORT:-22}" + +COCKPIT_LOCAL_PORT="${COCKPIT_LOCAL_PORT:-9090}" +Z2M_LOCAL_PORT="${Z2M_LOCAL_PORT:-8081}" +WEBUI_LOCAL_PORT="${WEBUI_LOCAL_PORT:-8099}" + +PORT_BASE="${PORT_BASE:-20000}" +PORT_SLOTS="${PORT_SLOTS:-4000}" + +ensure_autossh(){ + if ! command -v autossh >/dev/null 2>&1; then + log "Installing autossh..." + apt-get update -y + apt-get install -y autossh + fi +} + +compute_ports(){ + local hn="$1" + local crc slot cockpit z2m webui + crc="$(cksum <<<"$hn" | awk '{print $1}')" + slot="$(( crc % PORT_SLOTS ))" + cockpit="$(( PORT_BASE + slot*3 + 0 ))" + z2m="$(( PORT_BASE + slot*3 + 1 ))" + webui="$(( PORT_BASE + slot*3 + 2 ))" + echo "$cockpit $z2m $webui" +} + +ensure_key(){ + # IMPORTANT: + # - stdout: ONLY "edge_home|key|keypub" + # - any info/errors: stderr + + local hn="$1" + local edge_home ssh_dir key keypub + + if ! id -u "$EDGE_USER" >/dev/null 2>&1; then + echo "ERROR: EDGE user '$EDGE_USER' not found." >&2 + exit 1 + fi + + edge_home="$(getent passwd "$EDGE_USER" | cut -d: -f6)" + if [[ -z "${edge_home:-}" ]]; then + echo "ERROR: cannot resolve home for user '$EDGE_USER'." >&2 + exit 1 + fi + + ssh_dir="${edge_home}/.ssh" + key="${ssh_dir}/iomatex-${hn}" + keypub="${key}.pub" + + install -d -m 700 -o "$EDGE_USER" -g "$EDGE_USER" "$ssh_dir" + + if [[ ! -f "$key" || ! -f "$keypub" ]]; then + echo "Generating SSH key for ${EDGE_USER}..." >&2 + runuser -u "$EDGE_USER" -- ssh-keygen -t ed25519 -N "" -f "$key" -C "$hn" >/dev/null + else + echo "SSH key already exists: $key" >&2 + fi + + chmod 600 "$key" 2>/dev/null || true + chmod 644 "$keypub" 2>/dev/null || true + chown "$EDGE_USER:$EDGE_USER" "$key" "$keypub" 2>/dev/null || true + + runuser -u "$EDGE_USER" -- bash -lc "touch '$ssh_dir/known_hosts' && chmod 600 '$ssh_dir/known_hosts'" >/dev/null 2>&1 || true + + echo "$edge_home|$key|$keypub" +} + +write_wrapper(){ + local name="$1" + local local_port="$2" + local remote_port="$3" + local vps_user="$4" + local key="$5" + local edge_home="$6" + local wrapper="/usr/local/sbin/iomatex-rt-${name}.sh" + + cat > "$wrapper" < + + +HTML + +echo "[6/10] Write logo and favicon from source image" +if [ ! -f "$SRC_LOGO" ]; then + echo "ERROR: logo source image not found: $SRC_LOGO" >&2 + echo "Put source image here: $SCRIPT_DIR/iomatex_logo_source.png" >&2 + exit 1 +fi + +python3 - "$SRC_LOGO" "$APP_DIR/public/logo.png" "$APP_DIR/public/favicon.png" <<'PY' +import sys +from PIL import Image + +src = sys.argv[1] +logo_out = sys.argv[2] +fav_out = sys.argv[3] + +img = Image.open(src).convert("RGBA") + +logo = img.copy() +logo.thumbnail((96, 96)) +logo.save(logo_out, format="PNG") + +fav = img.copy() +fav.thumbnail((64, 64)) +fav.save(fav_out, format="PNG") + +print("Generated logo.png and favicon.png") +PY + +echo "[7/10] Write addon placeholders" +cat > "$ADDONS_BACKEND_DIR/README.txt" <<'TXT' +Place backend addons here as .js files. +Module format: +module.exports = function(app, ctx) { + app.get("/api/example", (req, res) => res.json({ ok: true })); +}; +TXT + +cat > "$ADDONS_PUBLIC_DIR/README.txt" <<'TXT' +Place frontend addons here as .js files. +They are auto-loaded from /api/addons after main UI boot. +Recommended addon file name = service key, for example: +mosquitto.js +bridge.js +z2m.js +Use window.IOMATEX_UI to access core state and helpers. +TXT + +echo "[8/10] npm install" +cd "$APP_DIR" +npm install --omit=dev + +echo "[9/10] Install systemd service" +cat > "/etc/systemd/system/${SERVICE_NAME}" <:${APP_PORT}" +echo "API health: curl -s http://127.0.0.1:${APP_PORT}/api/health | cat" +echo "Main services: curl -s http://127.0.0.1:${APP_PORT}/api/main/services | cat" +echo "Display API: curl -s http://127.0.0.1:${APP_PORT}/api/display/hdmi | cat" +echo "Addon list: curl -s http://127.0.0.1:${APP_PORT}/api/addons | cat" +echo "Service status: systemctl status ${SERVICE_NAME} --no-pager -n 40" +echo "Previous install: ${APP_DIR}.prev.${ts}" +echo "Backend addons dir: ${ADDONS_BACKEND_DIR}" +echo "Frontend addons dir: ${ADDONS_PUBLIC_DIR}" +echo "Logo source expected at: ${SRC_LOGO}" \ No newline at end of file diff --git a/Stage_branding/Desktop Wallpaper.png b/Stage_branding/Desktop Wallpaper.png new file mode 100755 index 0000000..e1caf94 Binary files /dev/null and b/Stage_branding/Desktop Wallpaper.png differ diff --git a/Stage_branding/stage_branding.sh b/Stage_branding/stage_branding.sh new file mode 100755 index 0000000..fb3bafe --- /dev/null +++ b/Stage_branding/stage_branding.sh @@ -0,0 +1,160 @@ +#!/usr/bin/env bash +set -euo pipefail +export DEBIAN_FRONTEND=noninteractive + +log(){ echo "[branding] $*"; } + +if [[ "${EUID}" -ne 0 ]]; then + echo "Run as root: sudo bash $0" + exit 1 +fi + +# ---- detect target user ---- +TARGET_USER="${SUDO_USER:-}" +if [[ -z "$TARGET_USER" || "$TARGET_USER" == "root" ]]; then + TARGET_USER="$(awk -F: '$3>=1000 && $1!="nobody" {print $1; exit}' /etc/passwd)" +fi + +TARGET_HOME="$(getent passwd "$TARGET_USER" | cut -d: -f6)" +DESKTOP_DIR="$TARGET_HOME/Desktop" + +mkdir -p "$DESKTOP_DIR" +mkdir -p "$TARGET_HOME/.config/autostart" +mkdir -p "$TARGET_HOME/.config/conky" + +chown -R "$TARGET_USER:$TARGET_USER" "$TARGET_HOME/.config" "$DESKTOP_DIR" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# ---- detect wallpaper ---- +WALLPAPER="" +for f in "$SCRIPT_DIR"/*.{png,jpg,jpeg}; do + [[ -f "$f" ]] || continue + WALLPAPER="$f" + break +done + +if [[ -z "$WALLPAPER" ]]; then + echo "No wallpaper image found next to script." + exit 1 +fi + +install -d /usr/share/backgrounds +WALL_DST="/usr/share/backgrounds/iomatex-wallpaper.${WALLPAPER##*.}" +install -m 0644 "$WALLPAPER" "$WALL_DST" + +# ---- install packages ---- +apt-get update -y +apt-get install -y --no-install-recommends \ + feh \ + xclock \ + xfce4-terminal \ + mbpoll \ + conky \ + curl \ + || true + +if apt-cache show qmodbus >/dev/null 2>&1; then + apt-get install -y qmodbus || true + HAS_QMODBUS=1 +else + HAS_QMODBUS=0 +fi + +# ---- wallpaper via feh ---- +log "Setting wallpaper via feh..." +sudo -u "$TARGET_USER" DISPLAY=:0 feh --bg-fill "$WALL_DST" || true + +cat > "$TARGET_HOME/.config/autostart/wallpaper.desktop" < "$TARGET_HOME/.config/autostart/clock.desktop" < "$DESKTOP_DIR/Terminal.desktop" </dev/null 2>&1; then + MODBUS_EXEC="qmodbus" + MODBUS_NAME="Modbus Tool (qmodbus)" +else + MODBUS_EXEC="xfce4-terminal -e mbpoll --help" + MODBUS_NAME="Modbus Tool (mbpoll)" +fi + +cat > "$DESKTOP_DIR/Modbus.desktop" < "$TARGET_HOME/.config/conky/cockpit.conf" <<'EOF' +conky.config = { + update_interval = 60, + double_buffer = true, + own_window = true, + own_window_type = 'desktop', + own_window_transparent = true, + alignment = 'top_right', + gap_x = 20, + gap_y = 40, + minimum_width = 300, + minimum_height = 80, + use_xft = true, + font = 'DejaVu Sans:size=11', +}; + +conky.text = [[ +Cockpit: + +${execi 300 curl -s ifconfig.me}:9090 +]]; +EOF + +cat > "$TARGET_HOME/.config/autostart/cockpit-widget.desktop" </dev/null || true + +chown -R "$TARGET_USER:$TARGET_USER" "$TARGET_HOME" + +log "Branding applied. Reboot or re-login X11 session." \ No newline at end of file diff --git a/Stage_help/stage_help.sh b/Stage_help/stage_help.sh new file mode 100755 index 0000000..aa12564 --- /dev/null +++ b/Stage_help/stage_help.sh @@ -0,0 +1,394 @@ +#!/usr/bin/env bash +set -euo pipefail + +# stage_help.sh +# This file is executed as a manifest step (type=bash). +# It also self-installs as a user command: /usr/local/bin/iomatex-help +# +# Features: +# - Stage0: Hostname / Cockpit / Time (always) +# - Stage1: MQTT status + cheat sheet (if installed) +# - Stage2: Zigbee2MQTT status + Web UI + config path + hints (if installed) +# - Health Check: FAILED units + filtered critical journal errors (no vendor noise) +# - Wi-Fi region: prints current regulatory domain (country code) +# - Colors: green=OK, red=bad, yellow=warn/info (auto-disabled if not a TTY) + +SELF_DST="/usr/local/bin/iomatex-help" + +# ---------------- Self-install (safe) ---------------- +self_install() { + local src dst + src="$(readlink -f "$0" 2>/dev/null || echo "$0")" + dst="$(readlink -f "$SELF_DST" 2>/dev/null || echo "$SELF_DST")" + + # If we already run from the final destination, do nothing. + [[ "$src" == "$dst" ]] && return 0 + + if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then + # Bootstrap runs as root, but manual runs may be non-root. + if command -v sudo >/dev/null 2>&1; then + exec sudo -E bash "$0" "$@" + else + echo "Run as root (sudo not found)." >&2 + exit 1 + fi + fi + + install -d /usr/local/bin + install -m 0755 "$src" "$SELF_DST" + + # Friendly message after install + echo + echo "======================================================" + echo " iomatex-help is your fast aid" + echo "======================================================" + local ip + ip="$(ip route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="src"){print $(i+1); exit}}' || true)" + if [[ -n "${ip:-}" ]]; then + echo " Use Cockpit at address: https://${ip}:9090" + else + echo " Use Cockpit at address: https://:9090" + fi + echo " Wi-Fi setup: sudo nmtui" + echo " Run: iomatex-help" + echo "======================================================" + echo +} + +if [[ "${1:-}" != "--no-install" ]]; then + self_install "$@" +fi + +have(){ command -v "$1" >/dev/null 2>&1; } + +# --- colors (auto-disable if not a TTY) --- +if [ -t 1 ]; then + C_RESET=$'\033[0m' + C_BOLD=$'\033[1m' + C_GREEN=$'\033[32m' + C_RED=$'\033[31m' + C_YELLOW=$'\033[33m' +else + C_RESET=""; C_BOLD=""; C_GREEN=""; C_RED=""; C_YELLOW="" +fi + +bold() { printf "%s%s%s\n" "${C_BOLD}" "$*" "${C_RESET}"; } +ok() { printf "%s%s%s\n" "${C_GREEN}" "$*" "${C_RESET}"; } +bad() { printf "%s%s%s\n" "${C_RED}" "$*" "${C_RESET}"; } +warn() { printf "%s%s%s\n" "${C_YELLOW}" "$*" "${C_RESET}"; } + +hr() { echo "------------------------------------------------------"; } +hr2() { echo "======================================================"; } + +print_kv() { + # print_kv "Key" "Value" "status" + # status: ok|bad|warn|plain + local k="$1" v="$2" st="${3:-plain}" + printf "%-15s : " "$k" + case "$st" in + ok) ok "$v" ;; + bad) bad "$v" ;; + warn) warn "$v" ;; + *) echo "$v" ;; + esac +} + +# Vendor / kernel / desktop noise to ignore in CRITICAL errors (priority=3). +NOISE_RE='fiq_debugger|fiq_debugger_probe|mpp|mpp[_-]|rockchip|dwhdmi|hdmi|spi-nand|arm-scmi|scmi|rk817|rk809|rk-multicodecs|rkvdec|rkvenc|rknpu|npu|pinctrl|spdif|ASoC|audio-routing|wdt87xx|i2c transfer failed|get feature failed|get desc failed|get device desc|autofs4|Tracker|tracker|metadata extractor|file system data miner|pulseaudio|ALSA woke us up|Most likely this is a bug in the ALSA driver|snd_pcm_avail|POLLIN|POLLOUT|dwc3|ep0out|remotectl|rk pwm remotectl|of_dma_request_slave_channel|Sap driver initialization failed|sap-server: Operation not permitted|Authentication algorithm number required' + +main_ipv4() { + local ip="" + ip="$(ip route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="src"){print $(i+1); exit}}' || true)" + [[ -n "${ip:-}" ]] && { echo "$ip"; return 0; } + ip="$(hostname -I 2>/dev/null | awk '{print $1}' || true)" + [[ -n "${ip:-}" ]] && echo "$ip" || echo "" +} + +wifi_regdomain() { + # Returns country code like "AE" or empty. + local reg="" + if have iw; then + reg="$(iw reg get 2>/dev/null | awk '/^country /{print $2; exit}' | sed 's/:.*//')" || true + fi + if [[ -z "${reg:-}" ]] && [[ -f /etc/modprobe.d/cfg80211.conf ]]; then + reg="$(grep -Eo 'ieee80211_regdom=[A-Z]{2}' /etc/modprobe.d/cfg80211.conf 2>/dev/null | head -n1 | cut -d= -f2)" || true + fi + [[ -n "${reg:-}" ]] && echo "$reg" || echo "" +} + +time_line() { + if have timedatectl; then + local tz ntp localtime + tz="$(timedatectl show -p Timezone --value 2>/dev/null || true)" + ntp="$(timedatectl show -p NTP --value 2>/dev/null || true)" + localtime="$(date '+%F %T %z' 2>/dev/null || date)" + echo "Time: ${localtime} (${tz:-unknown}) NTP=${ntp:-unknown}" + else + echo "Time: $(date 2>/dev/null || true)" + fi +} + +# ---------------- MQTT (Stage1) ---------------- +mqtt_pkg_installed() { + dpkg -s mosquitto >/dev/null 2>&1 +} + +mqtt_installed() { + [[ -f /etc/iomatex/mqtt_bridge.env ]] && return 0 + mqtt_pkg_installed && return 0 + systemctl list-unit-files 2>/dev/null | awk '{print $1}' | grep -qx "mosquitto.service" && return 0 + have mosquitto && return 0 + return 1 +} + +mqtt_running() { + systemctl is-active --quiet mosquitto 2>/dev/null && return 0 + pgrep -x mosquitto >/dev/null 2>&1 && return 0 + return 1 +} + +mqtt_listener_ok() { + have ss || return 1 + ss -lnt 2>/dev/null | grep -q "127.0.0.1:1883" +} + +mqtt_block() { + hr2 + bold "MQTT (Stage1)" + hr + + local device + device="$(hostname -s)" + + if mqtt_running; then + print_kv "Mosquitto" "running ✔" ok + else + if mqtt_installed; then + print_kv "Mosquitto" "installed but NOT running ✖" bad + else + print_kv "Mosquitto" "NOT installed ✖" bad + fi + fi + + if mqtt_listener_ok; then + print_kv "Listener" "127.0.0.1:1883 ✔" ok + else + if have ss; then + print_kv "Listener" "not detected ✖" bad + else + print_kv "Listener" "ss not available" warn + fi + fi + + if [[ -f /etc/iomatex/mqtt_bridge.env ]]; then + # shellcheck disable=SC1091 + source /etc/iomatex/mqtt_bridge.env 2>/dev/null || true + + local bridge="${ENABLE_BRIDGE:-unknown}" + if [[ "$bridge" == "1" ]]; then + print_kv "Bridge" "$bridge" ok + elif [[ "$bridge" == "0" ]]; then + print_kv "Bridge" "$bridge" warn + else + print_kv "Bridge" "$bridge" warn + fi + + if [[ -n "${REMOTE_HOST:-}" ]]; then + print_kv "Remote host" "${REMOTE_HOST}" ok + else + print_kv "Remote host" "not set" warn + fi + + print_kv "Remote port" "${REMOTE_PORT:-1883}" plain + print_kv "ClientID" "${REMOTE_CLIENTID:-${device}-bridge}" plain + else + print_kv "Bridge" "env not found" warn + fi + + hr + bold "MQTT cheat sheet" + hr + echo "Manual remote setup:" + if have iomatex-mqtt-remote-set; then + echo " sudo iomatex-mqtt-remote-set" + else + warn " (missing) expected: /usr/local/sbin/iomatex-mqtt-remote-set" + fi + + echo + echo "Edge -> Cloud test:" + if have mosquitto_pub; then + echo " mosquitto_pub -h 127.0.0.1 -t edge/test/hello -m 'edge-to-cloud'" + else + warn " mosquitto_pub not installed (apt-get install -y mosquitto-clients)" + fi + echo " MQTT Explorer topic:" + echo " iomatex/${device}/test/hello" + + echo + echo "Cloud -> Edge test:" + echo " Publish topic:" + echo " cloud/${device}/test/back" + echo " Payload:" + echo " cloud-to-edge" + + echo + echo " Receive locally:" + if have mosquitto_sub; then + echo " mosquitto_sub -h 127.0.0.1 -t 'edge/#' -v" + else + warn " mosquitto_sub not installed (apt-get install -y mosquitto-clients)" + fi +} + +# -------------- Zigbee2MQTT (Stage2) -------------- +z2m_installed() { + systemctl list-unit-files 2>/dev/null | awk '{print $1}' | grep -qx "zigbee2mqtt.service" && return 0 + [[ -d /opt/zigbee2mqtt ]] && return 0 + [[ -f /opt/zigbee2mqtt/data/configuration.yaml ]] && return 0 + have iomatex-help-z2m && return 0 + return 1 +} + +z2m_web_port_from_cfg() { + local cfg="$1" + local p="" + p="$(awk ' + BEGIN{f=0} + /^[[:space:]]*frontend:[[:space:]]*$/ {f=1; next} + f && /^[[:space:]]*port:[[:space:]]*/ {print $2; exit} + /^[[:alpha:]_]+:/ {if($1!="frontend:") f=0} + ' "$cfg" 2>/dev/null || true)" + [[ -n "${p:-}" ]] && echo "$p" || echo "8081" +} + +z2m_block() { + hr2 + bold "Zigbee2MQTT (Stage2)" + hr + + local svc="zigbee2mqtt" + local cfg="/opt/zigbee2mqtt/data/configuration.yaml" + local ip port ui + + ip="$(main_ipv4 || true)" + [[ -z "${ip:-}" ]] && ip="$(hostname -I 2>/dev/null | awk '{print $1}' || true)" + + if systemctl list-unit-files 2>/dev/null | awk '{print $1}' | grep -qx "zigbee2mqtt.service"; then + if systemctl is-active --quiet "$svc"; then + print_kv "Z2M status" "running ✔" ok + else + print_kv "Z2M status" "installed but NOT running ✖" bad + fi + else + if pgrep -f "zigbee2mqtt|/opt/zigbee2mqtt|index.js" >/dev/null 2>&1; then + print_kv "Z2M status" "running (no unit) ✔" ok + else + print_kv "Z2M status" "NOT installed" bad + fi + fi + + if [[ -f "$cfg" ]]; then + port="$(z2m_web_port_from_cfg "$cfg")" + ui="http://${ip:-}:${port}" + print_kv "Web UI" "$ui" ok + print_kv "Config" "$cfg" plain + else + print_kv "Web UI" "config not found" warn + print_kv "Config" "$cfg (missing)" warn + fi + + hr + bold "Hints" + hr + echo "More info:" + echo " iomatex-help-z2m" + echo + echo "How to view logs:" + echo " journalctl -u zigbee2mqtt -f" +} + +# ---------------- Health (filtered) ---------------- +health_block() { + hr2 + bold "IOMATEX SYSTEM HEALTH CHECK" + hr + echo "Host: $(hostname) Time: $(date -u +'%F %T UTC')" + hr + + bold "FAILED UNITS" + local failed + failed="$(systemctl --failed --no-legend 2>/dev/null || true)" + if [[ -z "${failed}" ]]; then + ok "OK: no failed units" + else + bad "${failed}" + fi + hr + + bold "CRITICAL ERRORS (this boot)" + local critical + critical="$(journalctl -p 3 -b --no-pager --quiet 2>/dev/null | grep -vE "$NOISE_RE" || true)" + + if [[ -z "${critical}" ]]; then + ok "OK: no critical errors" + hr + ok "SYSTEM STATUS: OK" + else + bad "${critical}" + hr + bad "SYSTEM STATUS: ATTENTION REQUIRED" + echo "Action:" + echo " 1) systemctl --failed" + echo " 2) journalctl -p 3 -b --no-pager" + fi +} + +main() { + local host ip reg + host="$(hostname 2>/dev/null || echo "unknown")" + ip="$(main_ipv4 || true)" + reg="$(wifi_regdomain || true)" + + hr2 + bold "IOMATEX HELP" + hr2 + + bold "Stage0 summary" + hr + echo "Hostname: ${host}" + if [[ -n "${ip:-}" ]]; then + echo "Cockpit: https://${ip}:9090" + else + warn "Cockpit: https://:9090" + fi + + if [[ -n "${reg:-}" ]]; then + echo "Wi-Fi region: ${reg}" + else + warn "Wi-Fi region: unknown" + fi + + echo "Wi-Fi setup: sudo nmtui" + + time_line + + if mqtt_installed; then + mqtt_block + else + hr2 + bold "MQTT (Stage1)" + hr + bad "MQTT is not installed yet." + warn "It is a critical component required for normal operation." + fi + + if z2m_installed; then + z2m_block + fi + + health_block + hr2 +} + +main "$@" \ No newline at end of file diff --git a/stage_env/IOMATEX_Stage0_cheatsheet.md b/stage_env/IOMATEX_Stage0_cheatsheet.md new file mode 100755 index 0000000..c714892 --- /dev/null +++ b/stage_env/IOMATEX_Stage0_cheatsheet.md @@ -0,0 +1,78 @@ +# IOMATEX Stage0 — шпаргалка (что сделано) + +1. **Логирование Stage0** + - Ведём лог в `/var/log/iomatex-stage0.log`. + +2. **PATH фикс глобально** + - Создан `/etc/profile.d/99-iomatex-path.sh` с системным PATH. + +3. **APT источники** + - Убран шум `bullseye-backports` из `/etc/apt/sources.list`. + - Удалены backports-листы из `/etc/apt/sources.list.d/`. + +4. **APT update** + - Выполнен `apt-get update`. + +5. **Базовые пакеты (минимальный набор для поддержки)** + - Установлены: `ca-certificates curl wget sudo openssh-server iproute2 net-tools tzdata htop mc nano rsync checkinstall xz-utils unzip git jq` + - (В v2 также: `procps dos2unix`) + +6. **Таймзона** + - Установлена `Asia/Dubai` (`/etc/localtime` + `dpkg-reconfigure tzdata`). + +7. **Пользователи (production-структура)** + - Создан/проверен `iomatex` (админ, в группе `sudo`). + - Создан/проверен `itscreen` (runtime user). + - (В v2 добавлен `zigbee2mqtt` (runtime user).) + - `itscreen` добавлен в группы `video,input,render`. + - `iomatex` добавлен в `adm,systemd-journal` (и при необходимости в аппаратные группы). + +8. **Hardening vendor user** + - `youngfeel` НЕ удаляем на Stage0. + - (В v2) `youngfeel`: пароль заблокирован, shell отключён, из `sudo` убран. + +9. **Структура каталогов /opt** + - Создано: + - `/opt/itscreen/{bin,data,logs}` + - `/opt/iomatex/{bin,conf,logs}` + - (В v2) `/opt/zigbee2mqtt/{app,data,logs}` + - Выставлены владельцы/права на каталоги. + +10. **Qt runtime зависимости** + - Установлены библиотеки для Qt/X11 (xcb) и EGL/DRM (conservative set). + +11. **SSH** + - `ssh` включён и перезапущен. + +12. **Device ID + hostname + branding** + - Device ID хранится в `/userdata/device-id` (создаётся, если нет). + - `hostname` = `g-box-xxxx`. + - `PrettyHostname` = `iomatex@g-box-xxxx`. + - Обновлён `/etc/hosts` строкой `127.0.1.1 `. + +13. **Cockpit** + - Установлен `cockpit`. + - Включён `cockpit.socket`. + - Добавлен баннер `/etc/issue.cockpit` + конфиг `/etc/cockpit/cockpit.conf`. + - Обновлён `/etc/motd`. + +14. **Local MQTT broker (Mosquitto)** + - Установлены `mosquitto` и `mosquitto-clients`. + - Создан основной конфиг `/etc/mosquitto/mosquitto.conf`. + - Приведён `conf.d` к виду без дублирующих `persistence*`. + - Создан MQTT пользователь (логин/пароль) в `/etc/mosquitto/passwd`: + - user: `iomatex` + - pass: `iomatex` + - Включён и перезапущен `mosquitto`, проверка listen `:1883`. + - Создано описание `/etc/iomatex-mqtt-readme.txt`. + - (В v2) Cloud bridge шаблон создан, но **выключен по умолчанию**. + +15. **Stage1.5 (опционально, если /userdata смонтирован)** + - Создан swap `/userdata/swapfile` (1GB) + запись в `/etc/fstab`. + - Настроен `vm.swappiness=10`. + - Миграция логов в `/userdata/var-log` и bind-mount в `/var/log`. + - Ограничены размеры journald (`/etc/systemd/journald.conf.d/99-iomatex.conf`). + +16. **Финальный summary** + - Печать параметров (hostname, IP, Cockpit URL, MQTT URL, layout /opt) + рекомендация reboot. + diff --git a/stage_env/stage_env.sh b/stage_env/stage_env.sh new file mode 100755 index 0000000..fb648c7 --- /dev/null +++ b/stage_env/stage_env.sh @@ -0,0 +1,918 @@ +#!/usr/bin/env bash +set -euo pipefail + +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +export DEBIAN_FRONTEND=noninteractive + +LOG="/var/log/iomatex-stage0_1.log" +mkdir -p /var/log >/dev/null 2>&1 || true +APT_UPDATED=0 +WRITE_CHANGED=0 + +log() { + local line="[$(date -u +'%F %T UTC')] $*" + echo "$line" + echo "$line" >>"$LOG" 2>/dev/null || true +} + +have() { + command -v "$1" >/dev/null 2>&1 +} + +backup_if_exists() { + local f="$1" + [ -e "$f" ] || return 0 + cp -a "$f" "${f}.bak.$(date +%F-%H%M%S)" || true +} + +main_ipv4() { + local ip="" + ip="$(ip route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="src"){print $(i+1); exit}}' || true)" + [ -n "${ip:-}" ] && { echo "$ip"; return 0; } + ip="$(hostname -I 2>/dev/null | awk '{print $1}' || true)" + [ -n "${ip:-}" ] && echo "$ip" || echo "" +} + +write_if_changed() { + local path="$1" + local mode="$2" + local owner="${3:-root}" + local group="${4:-root}" + local tmp + tmp="$(mktemp)" + cat >"$tmp" + + if [ -f "$path" ] && cmp -s "$tmp" "$path"; then + rm -f "$tmp" + chown "$owner:$group" "$path" 2>/dev/null || true + chmod "$mode" "$path" 2>/dev/null || true + WRITE_CHANGED=0 + return 0 + fi + + install -D -o "$owner" -g "$group" -m "$mode" "$tmp" "$path" + rm -f "$tmp" + WRITE_CHANGED=1 + return 0 +} + +package_installed() { + dpkg-query -W -f='${Status}\n' "$1" 2>/dev/null | grep -qx 'install ok installed' +} + +apt_update_if_needed() { + if [ "$APT_UPDATED" -eq 0 ]; then + run_long "APT update" 900 /usr/bin/apt-get update + APT_UPDATED=1 + else + log "APT update already completed in this run; skipping" + fi +} + +apt_install_missing() { + local pkgs=("$@") + local missing=() + local pkg + + for pkg in "${pkgs[@]}"; do + if ! package_installed "$pkg"; then + missing+=("$pkg") + fi + done + + if [ "${#missing[@]}" -eq 0 ]; then + log "Packages already installed: ${pkgs[*]}" + return 0 + fi + + apt_update_if_needed + run_long "Install packages" 1800 /usr/bin/apt-get install -y "${missing[@]}" +} + +apt_remove_if_installed() { + local pkgs=("$@") + local installed=() + local pkg + + for pkg in "${pkgs[@]}"; do + if package_installed "$pkg"; then + installed+=("$pkg") + fi + done + + if [ "${#installed[@]}" -eq 0 ]; then + log "Packages already absent: ${pkgs[*]}" + return 0 + fi + + run_long "Remove packages" 900 /usr/bin/apt-get remove -y "${installed[@]}" +} + +systemctl_try() { + /bin/systemctl "$@" >/dev/null 2>&1 || true +} + +systemctl_enable_now_safe() { + systemctl_try enable --now "$@" +} + +systemctl_restart_safe() { + systemctl_try restart "$@" +} + +systemctl_start_safe() { + systemctl_try start "$@" +} + +systemctl_disable_now_safe() { + systemctl_try disable --now "$@" +} + +systemctl_mask_safe() { + systemctl_try mask "$@" +} + +user_in_group() { + local user="$1" + local group="$2" + id -nG "$user" 2>/dev/null | tr ' ' '\n' | grep -qx "$group" +} + +ensure_group_membership() { + local user="$1" + shift + local changed=1 + local group + + for group in "$@"; do + if ! user_in_group "$user" "$group"; then + usermod -aG "$group" "$user" + changed=0 + fi + done + + return "$changed" +} + +step_n=0 +step() { + step_n=$((step_n+1)) + echo + echo "=== Step ${step_n}: $* ===" + log "STEP ${step_n}: $*" +} + +spinner() { + local pid="$1" + local msg="${2:-Working}" + local spin='|/-\' + local i=0 + + command -v tput >/dev/null 2>&1 && tput civis || true + while kill -0 "$pid" 2>/dev/null; do + i=$(( (i+1) % 4 )) + printf "\r[%c] %s..." "${spin:$i:1}" "$msg" + sleep 0.2 + done + printf "\r[✓] %s. \n" "$msg" + command -v tput >/dev/null 2>&1 && tput cnorm || true +} + +run_long() { + local msg="$1"; shift + local timeout_s="$1"; shift + log "RUN: $msg :: $*" + + if command -v timeout >/dev/null 2>&1; then + ( timeout "$timeout_s" "$@" >>"$LOG" 2>&1 ) & + else + ( "$@" >>"$LOG" 2>&1 ) & + fi + local pid=$! + spinner "$pid" "$msg" + wait "$pid" +} + +soft_run() { + local msg="$1"; shift + local timeout_s="$1"; shift + if run_long "$msg" "$timeout_s" "$@"; then + return 0 + else + log "SOFT-FAIL (ignored): $msg" + echo "[!] SOFT-FAIL (ignored): $msg (see $LOG)" + return 0 + fi +} + +# --- root --- +if [ "${EUID:-$(id -u)}" -ne 0 ]; then + if [ -x /usr/bin/sudo ]; then + exec /usr/bin/sudo -E /bin/bash "$0" "$@" + fi + echo "Need root. Please run: sudo bash $0" + exit 1 +fi + +# --- CRLF guard --- +if grep -q $'\r' "$0"; then + echo "[!] ERROR: Script has Windows CRLF line endings." + echo " Fix: sudo apt-get install -y dos2unix && dos2unix \"$0\"" + echo " Then rerun: sudo bash \"$0\"" + exit 1 +fi + +log "=== IOMATEX STAGE0_1 v3.2 START (Debian 11) ===" +log "LOG: $LOG" + +# ------------------------- +# Step 1: PATH fix +# ------------------------- +step "Fix PATH globally (survive vendor terminal)" +write_if_changed /etc/profile.d/99-iomatex-path.sh 0644 <<'EOF' +export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin +EOF + +# ------------------------- +# Step 2: APT sources normalize (official Debian 11 stable only) +# ------------------------- +step "APT sources normalize (official Debian 11 bullseye + non-free; remove vendor lists)" +backup_if_exists /etc/apt/sources.list + +write_if_changed /etc/apt/sources.list 0644 <<'EOF' +deb http://deb.debian.org/debian bullseye main contrib non-free +deb http://deb.debian.org/debian bullseye-updates main contrib non-free +deb http://security.debian.org/debian-security bullseye-security main contrib non-free +EOF + +rm -f /etc/apt/sources.list.d/*.list 2>/dev/null || true +log "APT sources normalized to official Debian 11 (no backports)" + +# ------------------------- +# Step 3: APT update +# ------------------------- +step "APT update" +apt_update_if_needed + +# ------------------------- +# Step 4: Base tools (nano mandatory early) +# ------------------------- +step "Install base tools (nano mandatory early) + checkinstall" +apt_install_missing \ + ca-certificates curl wget sudo \ + openssh-server \ + iproute2 net-tools \ + tzdata \ + htop mc \ + nano \ + rsync \ + checkinstall \ + xz-utils unzip git \ + jq \ + procps \ + dos2unix \ + network-manager \ + policykit-1 + +# ------------------------- +# Step 4.5: PulseAudio config sanitation +# ------------------------- +step "PulseAudio: sanitize default.pa (ES8388 + rescue-streams + tmp socket override) + client.conf tmp socket" +fix_pulseaudio_defaults() { + local pa="/etc/pulse/default.pa" + [ -f "$pa" ] || { log "PulseAudio default.pa not found, skip"; return 0; } + + cp -a "$pa" "${pa}.bak.$(date +%F-%H%M%S)" 2>/dev/null || true + + sed -i -E 's@^([[:space:]]*)(set-default-(sink|source)[[:space:]]+.*es8388.*)$@\1# \2@g' "$pa" + sed -i -E 's@^([[:space:]]*)load-module[[:space:]]+module-rescue-streams([[:space:]]|$).*@\1# load-module module-rescue-streams@g' "$pa" + sed -i -E 's@^([[:space:]]*)load-module[[:space:]]+module-native-protocol-unix.*socket=/tmp/pulse-socket.*$@\1load-module module-native-protocol-unix@g' "$pa" + + if [ -f /etc/pulse/client.conf ]; then + cp -a /etc/pulse/client.conf "/etc/pulse/client.conf.bak.$(date +%F-%H%M%S)" 2>/dev/null || true + sed -i -E 's@^([[:space:]]*default-server[[:space:]]*=[[:space:]]*unix:/tmp/pulse-socket[[:space:]]*)$@# \1@g' /etc/pulse/client.conf + fi + + log "PulseAudio config sanitized: $pa (+ client.conf)" +} +fix_pulseaudio_defaults + +# ------------------------- +# Step 5: Timezone Asia/Dubai +# ------------------------- +step "Timezone Asia/Dubai" +ln -sf /usr/share/zoneinfo/Asia/Dubai /etc/localtime +soft_run "dpkg-reconfigure tzdata" 120 /usr/sbin/dpkg-reconfigure -f noninteractive tzdata + +# ------------------------- +# Step 6: NTP (use systemd-timesyncd, remove ntp/ntpd) +# ------------------------- +step "Time sync: install+enable systemd-timesyncd; remove ntp/ntpd if present" +apt_install_missing systemd-timesyncd +systemctl_disable_now_safe ntp +systemctl_disable_now_safe ntpd +systemctl_mask_safe ntp.service +apt_remove_if_installed ntp +systemctl_enable_now_safe systemd-timesyncd +soft_run "timedatectl set-ntp true" 10 /bin/bash -lc 'timedatectl set-ntp true 2>/dev/null || true' + +# ------------------------- +# Step 7: Production users & hardening vendor user +# ------------------------- +step "Users: iomatex(admin) + itscreen(runtime) + zigbee2mqtt(runtime) + harden vendor user youngfeel" + +IOM_USER="iomatex" +IOM_PASS="iomatex" # default (must be changed on first login) +ITS_USER="itscreen" +Z2M_USER="zigbee2mqtt" + +ensure_user() { + local u="$1" + local shell="${2:-/usr/sbin/nologin}" + local home_flag="${3:--m}" + local current_shell="" + if ! id "$u" >/dev/null 2>&1; then + useradd $home_flag -s "$shell" "$u" + log "Created user: $u" + return 0 + else + log "User exists: $u" + current_shell="$(getent passwd "$u" | cut -d: -f7 || true)" + if [ -n "$shell" ] && [ "${current_shell:-}" != "$shell" ]; then + usermod -s "$shell" "$u" + log "Corrected shell for user ${u}: ${current_shell:-} -> ${shell}" + fi + return 1 + fi +} + +IOM_USER_CREATED=0 +if ensure_user "$IOM_USER" "/bin/bash" "-m"; then + IOM_USER_CREATED=1 + echo "$IOM_USER:$IOM_PASS" | chpasswd + log "Initialized default password for newly created user: $IOM_USER" +else + log "Preserving existing password for user: $IOM_USER" +fi +ensure_group_membership "$IOM_USER" sudo adm systemd-journal video input render plugdev netdev dialout audio || true + +ensure_user "$ITS_USER" "/usr/sbin/nologin" "-m" +ensure_user "$Z2M_USER" "/usr/sbin/nologin" "-m" + +ensure_group_membership "$ITS_USER" video input render dialout || true +ensure_group_membership "$Z2M_USER" dialout plugdev netdev || true + +if id youngfeel >/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 + soft_run "Set shell nologin youngfeel" 10 /usr/sbin/usermod -s /usr/sbin/nologin youngfeel + soft_run "Remove youngfeel from sudo group" 10 /bin/bash -lc 'gpasswd -d youngfeel sudo 2>/dev/null || true' +fi + +# ------------------------- +# Step 8: Security policy (pwquality + remove pam_unix obscure + force change) +# ------------------------- +step "Security: SIMPLE password policy (minlen=8, no dictionary) + remove pam_unix obscure + forced change" + +apt_install_missing libpam-pwquality + +write_if_changed /etc/security/pwquality.conf 0644 <<'EOF' +minlen = 8 +retry = 3 +dictcheck = 0 +EOF + +if ! grep -qE '^\s*password\s+requisite\s+pam_pwquality\.so' /etc/pam.d/common-password; then + sed -i '/pam_unix\.so/ i password requisite pam_pwquality.so retry=3' /etc/pam.d/common-password + log "Inserted pam_pwquality into /etc/pam.d/common-password" +fi + +if grep -qE 'pam_unix\.so.*\bobscure\b' /etc/pam.d/common-password; then + sed -i -E 's/(\bpam_unix\.so\b[^#\n]*)\bobscure\b[[:space:]]*/\1/g' /etc/pam.d/common-password + sed -i -E 's/[[:space:]]+/ /g' /etc/pam.d/common-password + log "Removed 'obscure' from pam_unix.so in /etc/pam.d/common-password" +fi + +if [ "$IOM_USER_CREATED" -eq 1 ]; then + soft_run "Force password change on first login for ${IOM_USER}" 10 /usr/bin/chage -d 0 "${IOM_USER}" +else + log "Skip forced password expiry for existing user: ${IOM_USER}" +fi + +write_if_changed /usr/local/sbin/iomatex-passwd 0755 <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +u="${1:-iomatex}" +if [ "$(id -u)" -ne 0 ]; then + exec sudo /usr/local/sbin/iomatex-passwd "$u" +fi +id "$u" >/dev/null 2>&1 || { echo "User not found: $u" >&2; exit 1; } +passwd "$u" +EOF + +# ------------------------- +# Step 9: LightDM autologin -> iomatex (NO restart here) +# ------------------------- +step "LightDM: set autologin-user=iomatex (apply after reboot; no screen restart now)" +if [ -f /etc/lightdm/lightdm.conf ]; then + backup_if_exists /etc/lightdm/lightdm.conf + + if grep -qE '^[[:space:]]*autologin-user[[:space:]]*=' /etc/lightdm/lightdm.conf; then + sed -i -E "s@^[[:space:]]*autologin-user[[:space:]]*=.*@autologin-user=${IOM_USER}@g" /etc/lightdm/lightdm.conf + else + if ! grep -qE '^\[Seat:\*\]' /etc/lightdm/lightdm.conf; then + printf "\n[Seat:*]\n" >> /etc/lightdm/lightdm.conf + fi + echo "autologin-user=${IOM_USER}" >> /etc/lightdm/lightdm.conf + fi + + if grep -qE '^[[:space:]]*autologin-user-timeout[[:space:]]*=' /etc/lightdm/lightdm.conf; then + sed -i -E "s@^[[:space:]]*autologin-user-timeout[[:space:]]*=.*@autologin-user-timeout=0@g" /etc/lightdm/lightdm.conf + else + echo "autologin-user-timeout=0" >> /etc/lightdm/lightdm.conf + fi + + log "LightDM autologin set to: ${IOM_USER} (timeout=0)" +else + log "LightDM config not found: /etc/lightdm/lightdm.conf (skipped)" +fi + +# ------------------------- +# Step 10: Chromium profile lock cleanup (safe) +# ------------------------- +step "Chromium: cleanup stale Singleton locks for iomatex (safe; does not delete profile)" +IOM_HOME="$(getent passwd "$IOM_USER" | cut -d: -f6)" +[ -n "${IOM_HOME:-}" ] || IOM_HOME="/home/${IOM_USER}" +soft_run "Remove chromium Singleton* locks (iomatex)" 20 /bin/bash -lc "rm -f '${IOM_HOME}/.config/chromium/Singleton'* 2>/dev/null || true" + +# ------------------------- +# Step 11: /opt layout (canonical) +# ------------------------- +step "Create canonical /opt layout" +install -d -o "$ITS_USER" -g "$ITS_USER" -m 0755 /opt/itscreen /opt/itscreen/bin /opt/itscreen/data /opt/itscreen/logs +install -d -o "$Z2M_USER" -g "$Z2M_USER" -m 0755 /opt/zigbee2mqtt /opt/zigbee2mqtt/app /opt/zigbee2mqtt/data /opt/zigbee2mqtt/logs +install -d -o root -g root -m 0755 /opt/iomatex /opt/iomatex/bin /opt/iomatex/conf /opt/iomatex/logs + +install -d -o "$ITS_USER" -g "$ITS_USER" -m 0755 /var/log/itscreen /var/lib/itscreen +install -d -o "$Z2M_USER" -g "$Z2M_USER" -m 0755 /var/log/zigbee2mqtt /var/lib/zigbee2mqtt + +# ------------------------- +# Step 12: Qt runtime deps (KEEP EXACT LIST) +# ------------------------- +step "Install Qt runtime dependencies (X11/xcb + common EGL/DRM libs)" +apt_install_missing \ + libgl1 libegl1 libgbm1 libdrm2 libinput10 \ + libx11-6 libxcb1 libxkbcommon0 libxkbcommon-x11-0 \ + libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-render-util0 \ + libxcb-xinerama0 libxcb-xkb1 libxcb-randr0 libxcb-shape0 libxcb-shm0 \ + libfontconfig1 libfreetype6 libdbus-1-3 || true + +# ------------------------- +# Step 13: SSH +# ------------------------- +step "Enable SSH" +systemctl_enable_now_safe ssh + +# ------------------------- +# Step 14: Hostname (8 hex) + branding +# ------------------------- +step "Set hostname (8 hex) + PrettyHostname (iomatex@g-box-xxxxxxxx)" +DEVICE_ID_FILE="/userdata/device-id" +DEVICE_ID="" +DEVICE_ID_RE='^g-box-[a-f0-9]{8}$' + +if [ -f "$DEVICE_ID_FILE" ]; then + DEVICE_ID="$(tr -d ' \n\r' < "$DEVICE_ID_FILE")" +fi + +if ! printf '%s\n' "${DEVICE_ID:-}" | grep -Eq "$DEVICE_ID_RE"; then + [ -n "${DEVICE_ID:-}" ] && log "Invalid device id in ${DEVICE_ID_FILE}: '${DEVICE_ID}' -> regenerating" + DEVICE_ID="g-box-$(cat /proc/sys/kernel/random/uuid | tr -d '-' | cut -c1-8)" + mkdir -p /userdata + echo "$DEVICE_ID" >"$DEVICE_ID_FILE" + chmod 0644 "$DEVICE_ID_FILE" || true +fi + +echo "$DEVICE_ID" >/etc/hostname +if have hostnamectl; then + hostnamectl set-hostname "$DEVICE_ID" || true +else + hostname "$DEVICE_ID" || true +fi + +BRAND_HOST="iomatex@${DEVICE_ID}" +if have hostnamectl; then + hostnamectl set-hostname "$BRAND_HOST" --pretty || true +fi + +if grep -qE '^127\.0\.1\.1' /etc/hosts; then + sed -i "s/^127\.0\.1\.1.*/127.0.1.1 $DEVICE_ID/" /etc/hosts +else + echo "127.0.1.1 $DEVICE_ID" >> /etc/hosts +fi + +log "Hostname set to: $DEVICE_ID (pretty: $BRAND_HOST) source: $DEVICE_ID_FILE" + +# ------------------------- +# Step 15: Cockpit + banner branding + password reminder +# ------------------------- +step "Install + enable Cockpit + branded banner + security reminder" +apt_install_missing cockpit cockpit-networkmanager cockpit-storaged cockpit-pcp network-manager +systemctl_enable_now_safe NetworkManager + +IP_MAIN="$(main_ipv4)" +[ -n "${IP_MAIN:-}" ] || IP_MAIN="" + +mkdir -p /etc/cockpit + +cat >/etc/issue.cockpit </etc/motd </dev/null 2>&1; then + iw reg set AE || true +fi + +mkdir -p /etc/modprobe.d +write_if_changed /etc/modprobe.d/cfg80211.conf 0644 <<'EOF' +options cfg80211 ieee80211_regdom=AE +EOF + +soft_run "Disable system wpa_supplicant" 30 /bin/systemctl disable --now wpa_supplicant || true + +mkdir -p /etc/NetworkManager +mkdir -p /etc/NetworkManager/conf.d +NM_CFG_CHANGED=0 +write_if_changed /etc/NetworkManager/conf.d/10-iomatex-main.conf 0644 root root <<'EOF' +[main] +plugins=keyfile + +[device] +wifi.scan-rand-mac-address=no +EOF +if [ "$WRITE_CHANGED" -eq 1 ]; then + NM_CFG_CHANGED=1 +fi + +write_if_changed /etc/NetworkManager/conf.d/99-iomatex-wifi.conf 0644 root root <<'EOF' +[keyfile] +unmanaged-devices=interface-name:p2p0;interface-name:p2p-dev-p2p0;interface-name:p2p-dev-wlan0 +EOF +if [ "$WRITE_CHANGED" -eq 1 ]; then + NM_CFG_CHANGED=1 +fi + +if [ "$NM_CFG_CHANGED" -eq 1 ]; then + soft_run "Restart NetworkManager" 30 /bin/systemctl restart NetworkManager +fi + +# ------------------------- +# Step 15.6: Fix Wi-Fi persistence after reboot (SYSTEM connections) - Debian 11 safe +# ------------------------- +step "NetworkManager: enforce SYSTEM Wi-Fi profiles (polkit rule + convert user:* profiles) (Debian 11-safe)" + +mkdir -p /etc/polkit-1/rules.d +POLKIT_RULE_CHANGED=0 +write_if_changed /etc/polkit-1/rules.d/10-iomatex-networkmanager.rules 0644 root root <<'EOF' +polkit.addRule(function(action, subject) { + if (subject.user == "iomatex") { + var a = action.id; + if (a == "org.freedesktop.NetworkManager.settings.modify.system" || + a == "org.freedesktop.NetworkManager.network-control" || + a == "org.freedesktop.NetworkManager.wifi.share.protected" || + a == "org.freedesktop.NetworkManager.wifi.share.open") { + return polkit.Result.YES; + } + } +}); +EOF +if [ "$WRITE_CHANGED" -eq 1 ]; then + POLKIT_RULE_CHANGED=1 +fi +if [ "$POLKIT_RULE_CHANGED" -eq 1 ]; then + soft_run "Restart polkit (best-effort)" 10 /bin/systemctl restart polkit || true +fi + +soft_run "Convert user Wi-Fi profiles -> system (Debian 11-safe)" 90 /bin/bash -lc ' +nmcli -t -f NAME,TYPE con show | while IFS=: read -r n t; do + [ -z "$n" ] && continue + case "$t" in wifi|802-11-wireless) ;; *) continue ;; esac + + perms=$(nmcli -g connection.permissions con show "$n" 2>/dev/null || true) + # normalize possible escaping: user\:iomatex -> user:iomatex + perms_norm=$(printf "%s" "$perms" | sed "s/\\\\:/:/g") + + case "$perms_norm" in + user:*) + nmcli con mod "$n" connection.permissions "" || true + nmcli con mod "$n" connection.autoconnect yes || true + nmcli con mod "$n" connection.autoconnect-priority 100 || true + nmcli con down "$n" >/dev/null 2>&1 || true + nmcli con up "$n" >/dev/null 2>&1 || true + ;; + esac +done +' + +soft_run "Restart NetworkManager (post-fix)" 30 /bin/systemctl restart NetworkManager + +REG_NOW="$(iw reg get 2>/dev/null | awk '/^country /{print $2; exit}' | sed 's/:.*//' || true)" +log "Wi-Fi hardening applied (Region=${REG_NOW:-unknown}, P2P ignored, NM-only mode)" +log "Wi-Fi persistence fix applied (SYSTEM profiles enforced + autoconnect-priority=100)" + +# ------------------------- +# Step 15.7: Wi-Fi bring-up (connect by UUID, late trigger, print status) - Debian 11 safe +# ------------------------- +step "Wi-Fi bring-up (connect by UUID, late trigger, print status) (Debian 11-safe)" + +WIFI_IFACE="wlan0" + +sleep 6 + +log "--- WIFI STATUS BEFORE ---" +nmcli -f DEVICE,TYPE,STATE,CONNECTION dev >>"$LOG" 2>&1 || true +nmcli -f GENERAL.STATE,GENERAL.REASON,GENERAL.CONNECTION dev show "$WIFI_IFACE" >>"$LOG" 2>&1 || true + +STATE_NOW="$(nmcli -g GENERAL.STATE dev show "$WIFI_IFACE" 2>/dev/null || true)" +log "wifi_state_before=${STATE_NOW:-}" + +if echo "${STATE_NOW:-}" | grep -q "100"; then + log "Wi-Fi already connected -> skip bring-up" +else + WIFI_UUID="" + + # Pick Wi-Fi UUID deterministically by max AUTOCONNECT-PRIORITY (among autoconnect=yes) + WIFI_UUID="$(nmcli -t -f UUID,TYPE,AUTOCONNECT,AUTOCONNECT-PRIORITY con show \ + | awk -F: '($2=="wifi" || $2=="802-11-wireless") && $3=="yes" { + p=$4; if(p=="") p=0; + if(best=="" || p>bestp){best=$1; bestp=p} + } + END{print best}')" + + # Fallback: any Wi-Fi profile + if [ -z "${WIFI_UUID:-}" ]; then + WIFI_UUID="$(nmcli -t -f UUID,TYPE con show \ + | awk -F: '($2=="wifi" || $2=="802-11-wireless") {print $1; exit}')" + fi + + WIFI_NAME="$(nmcli -g NAME con show uuid "$WIFI_UUID" 2>/dev/null || true)" + log "wifi_uuid_selected=${WIFI_UUID:-}" + log "wifi_name_selected=${WIFI_NAME:-}" + + if [ -n "${WIFI_UUID:-}" ] && [ -e "/sys/class/net/$WIFI_IFACE" ]; then + soft_run "Wi-Fi connect by UUID (best-effort)" 60 /bin/bash -lc " + nmcli networking on || true + nmcli radio wifi on || true + nmcli dev set '$WIFI_IFACE' managed yes || true + nmcli con up uuid '$WIFI_UUID' ifname '$WIFI_IFACE' || true + " + sleep 3 + else + log "WIFI_CONNECT_SKIP=YES (no uuid or iface missing)" + fi +fi + +log "--- WIFI STATUS AFTER ---" +nmcli -f DEVICE,TYPE,STATE,CONNECTION dev >>"$LOG" 2>&1 || true +nmcli -f GENERAL.STATE,GENERAL.REASON,GENERAL.CONNECTION dev show "$WIFI_IFACE" >>"$LOG" 2>&1 || true +# ------------------------- +# Step 16: /userdata usage (SAFE cold-boot) +# - NO bind-mount /var/log +# - NO fstab entries that can block boot +# - swap + app logs are enabled via systemd oneshot after /userdata is mounted +# ------------------------- +step "Userdata SAFE: systemd bootstrap (swap on /userdata + persistent app logs) + journald limits" + +mkdir -p /etc/systemd/system /usr/local/sbin + +write_if_changed /usr/local/sbin/iomatex-userdata-bootstrap 0755 <<'EOF' +#!/usr/bin/env bash +set -euo pipefail + +log() { echo "[iomatex-userdata-bootstrap] $*"; } + +ensure_link_target() { + local link_path="$1" + local target_path="$2" + + if [ -L "$link_path" ]; then + if [ "$(readlink "$link_path" 2>/dev/null || true)" = "$target_path" ]; then + return 0 + fi + rm -f "$link_path" + ln -s "$target_path" "$link_path" + return 0 + fi + + if [ -e "$link_path" ]; then + rm -rf "$link_path" + fi + + ln -s "$target_path" "$link_path" +} + +# Must be a mountpoint to proceed (prevents boot blocks) +if ! mountpoint -q /userdata; then + log "SKIP: /userdata is not mounted" + exit 0 +fi + +# 1) Swap on /userdata (no /etc/fstab usage) +SWAPFILE="/userdata/swapfile" +if command -v swapon >/dev/null 2>&1; then + if ! swapon --show=NAME | awk '{print $1}' | grep -qx "$SWAPFILE"; then + if [ ! -f "$SWAPFILE" ]; then + log "Create swapfile: $SWAPFILE (1024M)" + ( command -v fallocate >/dev/null 2>&1 && fallocate -l 1024M "$SWAPFILE" ) || dd if=/dev/zero of="$SWAPFILE" bs=1M count=1024 status=none + chmod 600 "$SWAPFILE" + mkswap "$SWAPFILE" >/dev/null + else + chmod 600 "$SWAPFILE" || true + file "$SWAPFILE" | grep -qi "swap file" || mkswap "$SWAPFILE" >/dev/null + fi + swapon "$SWAPFILE" || true + fi +fi + +# swappiness (harmless if already set) +echo "vm.swappiness=10" >/etc/sysctl.d/99-iomatex-swap.conf +sysctl -p /etc/sysctl.d/99-iomatex-swap.conf >/dev/null 2>&1 || true + +# 2) Persistent app logs on /userdata (NO bind of /var/log) +mkdir -p /userdata/logs/{itscreen,zigbee2mqtt,iomatex} +chown -R itscreen:itscreen /userdata/logs/itscreen 2>/dev/null || true +chown -R zigbee2mqtt:zigbee2mqtt /userdata/logs/zigbee2mqtt 2>/dev/null || true + +# Ensure classic dirs exist +mkdir -p /var/log/itscreen /var/log/zigbee2mqtt /opt/itscreen/logs /opt/zigbee2mqtt/logs /opt/iomatex/logs + +# Link /opt/*/logs -> /userdata/logs/* (stable for your apps) +ensure_link_target /opt/itscreen/logs /userdata/logs/itscreen +ensure_link_target /opt/zigbee2mqtt/logs /userdata/logs/zigbee2mqtt +ensure_link_target /opt/iomatex/logs /userdata/logs/iomatex + +# Optional: link /var/log/* (so existing tooling still sees logs) +ensure_link_target /var/log/itscreen /userdata/logs/itscreen +ensure_link_target /var/log/zigbee2mqtt /userdata/logs/zigbee2mqtt + +log "OK: swap + persistent logs configured (cold-boot safe)" +exit 0 +EOF + +USERDATA_UNIT_CHANGED=0 +write_if_changed /etc/systemd/system/iomatex-userdata-bootstrap.service 0644 <<'EOF' +[Unit] +Description=IOMATEX userdata bootstrap (swap + persistent logs) - cold-boot safe +After=local-fs.target +Wants=local-fs.target +ConditionPathIsDirectory=/userdata + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/iomatex-userdata-bootstrap +TimeoutStartSec=30 +RemainAfterExit=yes + +[Install] +WantedBy=multi-user.target +EOF +if [ "$WRITE_CHANGED" -eq 1 ]; then + USERDATA_UNIT_CHANGED=1 +fi + +if [ "$USERDATA_UNIT_CHANGED" -eq 1 ]; then + soft_run "systemd daemon-reload (userdata unit changed)" 20 /bin/systemctl daemon-reload +fi + +soft_run "Enable iomatex-userdata-bootstrap.service" 20 /bin/systemctl enable iomatex-userdata-bootstrap.service + +# journald limits (no bind mounts) +mkdir -p /etc/systemd/journald.conf.d +JOURNALD_CFG_CHANGED=0 +write_if_changed /etc/systemd/journald.conf.d/99-iomatex.conf 0644 <<'EOF' +[Journal] +SystemMaxUse=100M +RuntimeMaxUse=50M +MaxRetentionSec=7day +EOF +if [ "$WRITE_CHANGED" -eq 1 ]; then + JOURNALD_CFG_CHANGED=1 +fi +if [ "$JOURNALD_CFG_CHANGED" -eq 1 ]; then + soft_run "Restart systemd-journald" 30 /bin/systemctl restart systemd-journald +fi + +# Run bootstrap once now (best-effort) +soft_run "Run userdata bootstrap now (best-effort)" 30 /bin/systemctl start iomatex-userdata-bootstrap.service + +# ------------------------- +# Finish summary +# ------------------------- +step "Finish (health summary)" +log "=== IOMATEX STAGE0_1 v3.2 COMPLETE ===" +log "Hostname: $(hostname) (pretty: ${BRAND_HOST})" +log "User: iomatex (password MUST be changed on first login)" +log "Cockpit: https://${IP_MAIN}:9090" +log "Log file: $LOG" + +REG_NOW="$(iw reg get 2>/dev/null | awk '/^country /{print $2; exit}' | sed 's/:.*//' || true)" + +echo +echo "======================================================" +echo " IOMATEX EDGE :: STAGE0_1 COMPLETE" +echo "======================================================" +echo +echo " Hostname : $(hostname)" +echo " Pretty hostname : ${BRAND_HOST}" +echo " Device ID file : ${DEVICE_ID_FILE}" +echo +echo " Users:" +echo " - iomatex (admin, sudo) -> password MUST be changed on first login" +echo " Change via: Cockpit top-right → Account → Change password" +echo " Or CLI : sudo iomatex-passwd" +echo " - itscreen (runtime)" +echo " - zigbee2mqtt (runtime)" +echo " - youngfeel (hardened/disabled if existed)" +echo +echo " Password policy : minlen=8 (NO dictionary), pam_unix obscure OFF" +echo " LightDM autologin: ${IOM_USER} (applies after reboot)" +echo " Chromium: Singleton locks cleaned for ${IOM_USER}" +echo +echo " Wi-Fi region : ${REG_NOW:-unknown}" +echo " Wi-Fi persistence: SYSTEM profiles enforced (no login required)" +echo " Wi-Fi management : use command -> sudo nmtui" +echo +echo " Userdata usage (cold-boot safe):" +echo " - swap on /userdata via systemd oneshot (no fstab)" +echo " - persistent logs in /userdata/logs/* (no /var/log bind mount)" +echo +echo " Network IPs:" +ip -4 addr show | awk '/inet /{print " - " $2 " (" $NF ")"}' || true +echo +echo " Cockpit : https://${IP_MAIN}:9090" +echo +echo " /opt layout:" +echo " - /opt/itscreen/{bin,data,logs} (logs -> /userdata/logs/itscreen)" +echo " - /opt/zigbee2mqtt/{app,data,logs} (logs -> /userdata/logs/zigbee2mqtt)" +echo " - /opt/iomatex/{bin,conf,logs} (logs -> /userdata/logs/iomatex)" +echo +echo " Time sync:" +timedatectl status 2>/dev/null | sed -n '1,12p' || true +echo +echo " DONE. Recommended next step: reboot" +echo diff --git a/stage_wifi_setup/stage0_1_ap.sh b/stage_wifi_setup/stage0_1_ap.sh new file mode 100644 index 0000000..09f4b51 --- /dev/null +++ b/stage_wifi_setup/stage0_1_ap.sh @@ -0,0 +1,730 @@ +#!/usr/bin/env bash +set -euo pipefail + +# ====================================== +# IOMATEX FAILOVER AP + WiFi Setup UI +# Debian 11 / NetworkManager +# Single Wi-Fi card: wlan0 +# +# Working policy intentionally preserved: +# - Uplink OK via eth0 carrier OR wlan0 STA (NM connected + IPv4) => AP OFF +# - Else => AP ON (wlan0 AP), captive HTTP(80) -> UI +# - UI "Connect" => AP down -> try STA connect -> if fail -> AP back +# +# Defaults: +# - AP SSID = hostname +# - AP PASS = iomatex123 +# - AP IP = 10.10.10.1/24 +# - UI port = 18080 +# ====================================== + +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +export DEBIAN_FRONTEND=noninteractive + +LOG="/var/log/iomatex-stage0_1_ap.log" +mkdir -p /var/log >/dev/null 2>&1 || true +touch "$LOG" >/dev/null 2>&1 || true +exec > >(tee -a "$LOG") 2>&1 + +IFACE="wlan0" +AP_IP="10.10.10.1" +AP_CIDR="${AP_IP}/24" +DHCP_START="10.10.10.50" +DHCP_END="10.10.10.150" +DHCP_LEASE="12h" +UI_PORT="18080" +SSID="$(hostname -s)" +PASS="iomatex123" +COUNTRY_CODE="NL" +AP_CHANNEL="6" + +APT_UPDATED=0 +LAST_WRITE_CHANGED=0 +SYSTEMD_UNITS_CHANGED=0 +UI_SERVICE_CHANGED=0 +WATCH_SERVICE_CHANGED=0 + +log() { + local line="[$(date -u +'%F %T UTC')] $*" + echo "$line" +} + +step_n=0 +step() { + step_n=$((step_n + 1)) + echo + echo "=== Step ${step_n}: $* ===" + log "STEP ${step_n}: $*" +} + +need_root() { + if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then + echo "ERROR: Run as root: sudo bash $0" >&2 + exit 1 + fi +} + +check_text_safety() { + 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)." >&2 + exit 1 + fi +} + +have() { + command -v "$1" >/dev/null 2>&1 +} + +backup_if_exists() { + local path="$1" + local ts + ts="$(date +%Y%m%d-%H%M%S)" + [[ -e "$path" ]] && cp -a "$path" "${path}.bak.${ts}" || true +} + +write_managed_file() { + local path="$1" + local mode="$2" + local owner="${3:-root}" + local group="${4:-root}" + local tmp + + tmp="$(mktemp)" + cat >"$tmp" + + if [[ -f "$path" ]] && cmp -s "$tmp" "$path"; then + rm -f "$tmp" + chown "$owner:$group" "$path" 2>/dev/null || true + chmod "$mode" "$path" 2>/dev/null || true + LAST_WRITE_CHANGED=0 + return 0 + fi + + backup_if_exists "$path" + install -D -o "$owner" -g "$group" -m "$mode" "$tmp" "$path" + rm -f "$tmp" + LAST_WRITE_CHANGED=1 + return 0 +} + +mark_unit_change_if_needed() { + if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then + SYSTEMD_UNITS_CHANGED=1 + fi +} + +package_installed() { + dpkg-query -W -f='${Status}\n' "$1" 2>/dev/null | grep -qx 'install ok installed' +} + +apt_update_if_needed() { + if [[ "$APT_UPDATED" -eq 0 ]]; then + log "RUN: apt-get update" + apt-get update -y + APT_UPDATED=1 + else + log "APT update already done in this run; skipping" + fi +} + +apt_install_missing() { + local missing=() + local pkg + + for pkg in "$@"; do + if ! package_installed "$pkg"; then + missing+=("$pkg") + fi + done + + if [[ "${#missing[@]}" -eq 0 ]]; then + log "Packages already installed: $*" + return 0 + fi + + apt_update_if_needed + log "RUN: apt-get install -y ${missing[*]}" + apt-get install -y "${missing[@]}" +} + +systemctl_try() { + systemctl "$@" >/dev/null 2>&1 || true +} + +systemctl_enable_now_safe() { + systemctl_try enable --now "$@" +} + +systemctl_restart_safe() { + systemctl_try restart "$@" +} + +systemctl_start_safe() { + systemctl_try start "$@" +} + +systemctl_disable_now_safe() { + systemctl_try disable --now "$@" +} + +ensure_nm_wifi_profile() { + local profile_name="$1" + local wifi_ssid="$2" + local wifi_pass="$3" + local existing_type="" + + existing_type="$(nmcli -g connection.type con show "$profile_name" 2>/dev/null || true)" + + case "$existing_type" in + "" ) + nmcli con add type wifi ifname "$IFACE" con-name "$profile_name" ssid "$wifi_ssid" >/dev/null + ;; + wifi|802-11-wireless) + nmcli con mod "$profile_name" connection.interface-name "$IFACE" 802-11-wireless.ssid "$wifi_ssid" >/dev/null + ;; + * ) + # Unavoidable collision: preserve current behavior while avoiding blind delete in the normal case. + nmcli con delete id "$profile_name" >/dev/null 2>&1 || true + nmcli con add type wifi ifname "$IFACE" con-name "$profile_name" ssid "$wifi_ssid" >/dev/null + ;; + esac + + if [[ -n "$wifi_pass" ]]; then + nmcli con mod "$profile_name" wifi-sec.key-mgmt wpa-psk wifi-sec.psk "$wifi_pass" >/dev/null + else + nmcli con mod "$profile_name" wifi-sec.key-mgmt none >/dev/null 2>&1 || true + fi + + nmcli con mod "$profile_name" \ + connection.autoconnect yes \ + connection.autoconnect-priority 10 \ + ipv4.method auto \ + ipv6.method ignore >/dev/null +} + +need_root +check_text_safety + +log "=== IOMATEX FAILOVER AP + WiFi Setup START ===" +log "LOG: $LOG" + +step "Install packages" +apt_install_missing hostapd dnsmasq iw rfkill python3 network-manager iptables + +step "Prefer iptables-legacy if available" +if update-alternatives --list iptables >/dev/null 2>&1; then + update-alternatives --set iptables /usr/sbin/iptables-legacy >/dev/null 2>&1 || true +fi +if update-alternatives --list ip6tables >/dev/null 2>&1; then + update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy >/dev/null 2>&1 || true +fi + +step "Disable stock hostapd and dnsmasq" +systemctl_disable_now_safe hostapd +systemctl_disable_now_safe dnsmasq + +step "Write managed configs" +mkdir -p /etc/iomatex /etc/hostapd /etc/dnsmasq.d /opt/iomatex-wifi-ui /usr/local/sbin + +write_managed_file /etc/iomatex/ap.env 0644 < AP +address=/#/$AP_IP +EOF + +step "Write managed systemd units and UI app" +write_managed_file /etc/systemd/system/iomatex-hostapd.service 0644 <<'EOF' +[Unit] +Description=IOMATEX hostapd (AP) +After=network.target +Wants=network.target + +[Service] +Type=simple +ExecStart=/usr/sbin/hostapd -dd /etc/hostapd/iomatex-ap.conf +Restart=on-failure +RestartSec=2 + +[Install] +WantedBy=multi-user.target +EOF +mark_unit_change_if_needed + +write_managed_file /etc/systemd/system/iomatex-dnsmasq.service 0644 <<'EOF' +[Unit] +Description=IOMATEX dnsmasq (DHCP/DNS for AP) +After=network.target +Wants=network.target + +[Service] +Type=simple +ExecStart=/usr/sbin/dnsmasq --no-daemon --conf-file=/etc/dnsmasq.d/iomatex-ap.conf +Restart=on-failure +RestartSec=2 + +[Install] +WantedBy=multi-user.target +EOF +mark_unit_change_if_needed + +write_managed_file /opt/iomatex-wifi-ui/app.py 0755 <<'PY' +#!/usr/bin/env python3 +import json +import subprocess +import urllib.parse +from http.server import BaseHTTPRequestHandler, HTTPServer + + +def load_env(path="/etc/iomatex/ap.env"): + data = {} + try: + with open(path, "r", encoding="utf-8", errors="ignore") as fh: + for line in fh: + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, value = line.split("=", 1) + data[key.strip()] = value.strip().strip('"').strip("'") + except Exception: + pass + return data + + +ENV = load_env() +UI_PORT = int(ENV.get("UI_PORT", "18080")) + + +def run(cmd): + proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + return proc.returncode, (proc.stdout or "").strip() + + +HTML = """ + +IOMATEX Wi-Fi Setup + +

IOMATEX Wi-Fi Setup

+ +
+ Status +
Loading...
+ +
+ +
+ Connect to external Wi-Fi +
In AP mode scanning may be unavailable; enter SSID manually.
+ + +
+
+
+ + + +""" + + +class Handler(BaseHTTPRequestHandler): + def address_string(self): + return self.client_address[0] + + def log_message(self, fmt, *args): + return + + def _send(self, code, body, content_type): + payload = body.encode("utf-8") if isinstance(body, str) else body + self.send_response(code) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + def do_GET(self): + if self.path.startswith("/api/status"): + rc, out = run(["/usr/local/sbin/iomatex-wifi-status"]) + self._send(200, json.dumps({"ok": rc == 0, "output": out}), "application/json") + return + self._send(200, HTML, "text/html; charset=utf-8") + + def do_POST(self): + if self.path.startswith("/api/connect"): + size = int(self.headers.get("Content-Length", "0")) + data = self.rfile.read(size).decode("utf-8", "ignore") + form = urllib.parse.parse_qs(data) + ssid = (form.get("ssid", [""])[0] or "").strip() + password = (form.get("pass", [""])[0] or "") + if not ssid: + self._send(400, json.dumps({"ok": False, "output": "SSID required"}), "application/json") + return + rc, out = run(["/usr/local/sbin/iomatex-wifi-setup", ssid, password]) + self._send(200, json.dumps({"ok": rc == 0, "rc": rc, "output": out}), "application/json") + return + self._send(404, "Not Found", "text/plain; charset=utf-8") + + +def main(): + HTTPServer.allow_reuse_address = True + HTTPServer(("0.0.0.0", UI_PORT), Handler).serve_forever() + + +if __name__ == "__main__": + main() +PY +if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then + UI_SERVICE_CHANGED=1 +fi + +write_managed_file /etc/systemd/system/iomatex-wifi-ui.service 0644 <<'EOF' +[Unit] +Description=IOMATEX Wi-Fi Setup UI +After=network.target +Wants=network.target + +[Service] +Type=simple +ExecStart=/usr/bin/python3 /opt/iomatex-wifi-ui/app.py +Restart=on-failure +RestartSec=2 + +[Install] +WantedBy=multi-user.target +EOF +mark_unit_change_if_needed +if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then + UI_SERVICE_CHANGED=1 +fi + +step "Write control scripts" +write_managed_file /usr/local/sbin/iomatex-ap-up 0755 <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/ap.env + +rfkill unblock all >/dev/null 2>&1 || true + +if command -v nmcli >/dev/null 2>&1; then + nmcli dev disconnect "$IFACE" >/dev/null 2>&1 || true + nmcli dev set "$IFACE" managed no >/dev/null 2>&1 || true +fi + +ip link set "$IFACE" up >/dev/null 2>&1 || true +ip addr flush dev "$IFACE" >/dev/null 2>&1 || true +ip addr add "$AP_CIDR" dev "$IFACE" + +systemctl start iomatex-dnsmasq.service +systemctl start iomatex-hostapd.service + +# Captive: ONLY HTTP -> UI (no HTTPS DNAT) +iptables -t nat -D PREROUTING -i "$IFACE" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} 2>/dev/null || true +iptables -t nat -A PREROUTING -i "$IFACE" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} 2>/dev/null || true +EOF + +write_managed_file /usr/local/sbin/iomatex-ap-down 0755 <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/ap.env + +systemctl stop iomatex-hostapd.service 2>/dev/null || true +systemctl stop iomatex-dnsmasq.service 2>/dev/null || true + +iptables -t nat -D PREROUTING -i "$IFACE" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} 2>/dev/null || true + +ip addr flush dev "$IFACE" 2>/dev/null || true + +if command -v nmcli >/dev/null 2>&1; then + nmcli dev set "$IFACE" managed yes >/dev/null 2>&1 || true +fi +EOF + +write_managed_file /usr/local/sbin/iomatex-wifi-status 0755 <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/ap.env + +ap_active=0 +systemctl is-active --quiet iomatex-hostapd.service && ap_active=1 + +nm_state="n/a" +nm_con="n/a" +if command -v nmcli >/dev/null 2>&1; then + nm_state="$(nmcli -t -f DEVICE,STATE dev | awk -F: -v d="$IFACE" '$1==d{print $2; exit}' || true)" + nm_con="$(nmcli -t -f DEVICE,CONNECTION dev | awk -F: -v d="$IFACE" '$1==d{print $2; exit}' || true)" +fi + +sta_connected=no +if command -v iw >/dev/null 2>&1; then + iw dev "$IFACE" link 2>/dev/null | grep -q "^Connected to " && sta_connected=yes +fi + +ip4="$(ip -4 -o addr show dev "$IFACE" 2>/dev/null | awk '{print $4}' | head -n1 || true)" + +echo "IFACE=$IFACE" +echo "AP_ACTIVE=$ap_active" +echo "NM_STATE=$nm_state" +echo "NM_CONNECTION=$nm_con" +echo "STA_CONNECTED=$sta_connected" +echo "IP4=$ip4" +echo "WATCH_STATE=$(cat /run/iomatex-ap.state 2>/dev/null || echo n/a)" +EOF + +write_managed_file /usr/local/sbin/iomatex-wifi-setup 0755 <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/ap.env + +SSID_IN="${1:-}" +PASS_IN="${2:-}" + +[ -n "$SSID_IN" ] || { echo "ERROR: SSID required" >&2; exit 2; } +command -v nmcli >/dev/null 2>&1 || { echo "ERROR: nmcli not found" >&2; exit 3; } + +LOCK="/run/iomatex-wifi-setup.lock" +exec 9>"$LOCK" +flock -n 9 || { echo "ERROR: busy" >&2; exit 4; } + +CN="$(echo "$SSID_IN" | tr -cd "[:alnum:] ._-" | sed -E "s/[[:space:]]+/ /g" | cut -c1-64)" +[ -n "$CN" ] || CN="iomatex-wifi" + +sta_ok() { + nmcli -t -f DEVICE,STATE dev | grep -q "^${IFACE}:connected$" || return 1 + ip -4 -o addr show dev "$IFACE" 2>/dev/null | grep -q "inet " || return 1 + return 0 +} + +/usr/local/sbin/iomatex-ap-down >/dev/null 2>&1 || true + +nmcli dev set "$IFACE" managed yes >/dev/null 2>&1 || true +ip addr flush dev "$IFACE" >/dev/null 2>&1 || true +ip link set "$IFACE" up >/dev/null 2>&1 || true + +existing_type="$(nmcli -g connection.type con show "$CN" 2>/dev/null || true)" +case "$existing_type" in + "" ) + nmcli con add type wifi ifname "$IFACE" con-name "$CN" ssid "$SSID_IN" >/dev/null + ;; + wifi|802-11-wireless) + nmcli con mod "$CN" connection.interface-name "$IFACE" 802-11-wireless.ssid "$SSID_IN" >/dev/null + ;; + * ) + nmcli con delete id "$CN" >/dev/null 2>&1 || true + nmcli con add type wifi ifname "$IFACE" con-name "$CN" ssid "$SSID_IN" >/dev/null + ;; +esac + +if [ -n "$PASS_IN" ]; then + nmcli con mod "$CN" wifi-sec.key-mgmt wpa-psk wifi-sec.psk "$PASS_IN" >/dev/null +else + nmcli con mod "$CN" wifi-sec.key-mgmt none >/dev/null 2>&1 || true +fi + +nmcli con mod "$CN" connection.autoconnect yes connection.autoconnect-priority 10 ipv4.method auto ipv6.method ignore >/dev/null +nmcli dev disconnect "$IFACE" >/dev/null 2>&1 || true +nmcli con up id "$CN" >/dev/null 2>&1 || true + +sleep 10 + +if sta_ok; then + { echo "WIFI_PROFILE=\"$CN\""; echo "WIFI_SSID=\"$SSID_IN\""; } > /etc/iomatex/wifi.env + chmod 0644 /etc/iomatex/wifi.env + echo "OK: STA connected (profile=$CN)" + exit 0 +fi + +/usr/local/sbin/iomatex-ap-up >/dev/null 2>&1 || true +echo "ERROR: STA not connected / no IPv4; AP restored" >&2 +exit 10 +EOF + +step "Write watcher" +write_managed_file /usr/local/sbin/iomatex-ap-watch 0755 <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/ap.env + +STATE="/run/iomatex-ap.state" +LOCK="/run/iomatex-ap.lock" +exec 9>"$LOCK" +flock -n 9 || exit 0 + +eth_ok() { + [ "$(cat /sys/class/net/eth0/carrier 2>/dev/null || echo 0)" = "1" ] || return 1 + return 0 +} + +sta_ok() { + command -v nmcli >/dev/null 2>&1 || return 1 + nmcli -t -f DEVICE,STATE dev | grep -q "^${IFACE}:connected$" || return 1 + ip -4 -o addr show dev "$IFACE" 2>/dev/null | grep -q "inet " || return 1 + return 0 +} + +ap_is_up() { systemctl is-active --quiet iomatex-hostapd.service; } + +if eth_ok || sta_ok; then + ap_is_up && /usr/local/sbin/iomatex-ap-down || true + echo "uplink_ok" > "$STATE" + exit 0 +fi + +ap_is_up || /usr/local/sbin/iomatex-ap-up +echo "ap_on_no_uplink" > "$STATE" +EOF +if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then + WATCH_SERVICE_CHANGED=1 +fi + +write_managed_file /etc/systemd/system/iomatex-ap-watch.service 0644 <<'EOF' +[Unit] +Description=IOMATEX AP Watch +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/iomatex-ap-watch +EOF +mark_unit_change_if_needed +if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then + WATCH_SERVICE_CHANGED=1 +fi + +write_managed_file /etc/systemd/system/iomatex-ap-watch.timer 0644 <<'EOF' +[Unit] +Description=IOMATEX AP Watch timer + +[Timer] +OnBootSec=20 +OnUnitActiveSec=15 +AccuracySec=2 +Unit=iomatex-ap-watch.service + +[Install] +WantedBy=timers.target +EOF +mark_unit_change_if_needed +if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then + WATCH_SERVICE_CHANGED=1 +fi + +step "Enable services and apply only needed reloads" +if [[ "$SYSTEMD_UNITS_CHANGED" -eq 1 ]]; then + systemctl daemon-reload +fi + +systemctl enable iomatex-wifi-ui.service >/dev/null 2>&1 || true +systemctl enable iomatex-ap-watch.timer >/dev/null 2>&1 || true + +if [[ "$UI_SERVICE_CHANGED" -eq 1 ]]; then + if systemctl is-active --quiet iomatex-wifi-ui.service; then + systemctl_restart_safe iomatex-wifi-ui.service + else + systemctl_start_safe iomatex-wifi-ui.service + fi +else + systemctl_start_safe iomatex-wifi-ui.service +fi + +if [[ "$WATCH_SERVICE_CHANGED" -eq 1 ]]; then + if systemctl is-active --quiet iomatex-ap-watch.timer; then + systemctl_restart_safe iomatex-ap-watch.timer + else + systemctl_start_safe iomatex-ap-watch.timer + fi +else + systemctl_start_safe iomatex-ap-watch.timer +fi + +step "Initial enforce" +/usr/local/sbin/iomatex-ap-watch || true + +step "Quick self-test" +curl -m 2 -fsS "http://127.0.0.1:${UI_PORT}/api/status" >/dev/null 2>&1 || true + +echo +echo "=== INSTALL DONE ===" +echo "AP SSID : ${SSID}" +echo "AP PASS : ${PASS}" +echo "AP IP : ${AP_IP}" +echo "UI : http://${AP_IP}:${UI_PORT} (also: http://${AP_IP} via captive HTTP)" +echo +echo "TEST:" +echo " - No uplink (unplug eth / no STA): connect to WiFi SSID=${SSID}" +echo " - Open: http://10.10.10.1 (NOT https)" +echo +echo "DIAG:" +echo " /usr/local/sbin/iomatex-wifi-status" +echo " systemctl status iomatex-wifi-ui.service iomatex-ap-watch.timer --no-pager" +echo " journalctl -u iomatex-wifi-ui.service -u iomatex-ap-watch.service --no-pager -n 200" diff --git a/stage_wifi_setup/stage0_1_ap_eth.sh b/stage_wifi_setup/stage0_1_ap_eth.sh new file mode 100755 index 0000000..3b34cee --- /dev/null +++ b/stage_wifi_setup/stage0_1_ap_eth.sh @@ -0,0 +1,708 @@ +#!/usr/bin/env bash +set -euo pipefail + +# ====================================== +# IOMATEX FAILBACK (FINAL, PRODUCTION-SAFE, NO-GRACE) +# Debian 11 / NetworkManager +# +# Modes: +# A) eth0 production uplink (IPv4 + default route via eth0) -> AP OFF, ETH failback OFF +# B) eth0 cable present but NO production uplink -> AP OFF, ETH failback ON (10.10.10.2/24 + DHCP) +# C) no eth0 cable: +# - if Wi-Fi STA connected -> AP OFF +# - else -> AP ON (10.10.10.1/24 + captive HTTP->UI) +# +# UI: +# - always listens on 0.0.0.0:18080 (reachable via AP/ETH/STA IP) +# +# Addresses: +# - wlan0 AP : 10.10.10.1/24 +# - eth0 FB : 10.10.10.2/24 +# +# ====================================== + +# --- Notepad++/Windows safety guards (BOM + CRLF) --- +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 in Notepad++." >&2 + exit 1 +fi + +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +export DEBIAN_FRONTEND=noninteractive + +LOG="/var/log/iomatex-failback-install.log" +mkdir -p /var/log >/dev/null 2>&1 || true +exec > >(tee -a "$LOG") 2>&1 + +# ---------- Config ---------- +WLAN_IF="wlan0" +ETH_IF="eth0" + +AP_IP="10.10.10.1" +AP_CIDR="${AP_IP}/24" +AP_DHCP_START="10.10.10.50" +AP_DHCP_END="10.10.10.150" +AP_DHCP_LEASE="12h" + +ETH_FB_IP="10.10.10.2" +ETH_FB_CIDR="${ETH_FB_IP}/24" +ETH_DHCP_START="10.10.10.200" +ETH_DHCP_END="10.10.10.230" +ETH_DHCP_LEASE="12h" + +UI_PORT="18080" +AP_SSID="$(hostname -s)" +AP_PASS="iomatex123" +COUNTRY_CODE="NL" +AP_CHANNEL="6" + +ts="$(date +%Y%m%d-%H%M%S)" +backup_if_exists() { local f="$1"; [[ -e "$f" ]] && cp -a "$f" "${f}.bak.${ts}" || true; } + +echo "=== IOMATEX Failback installer (FINAL, prod-safe, no-grace) ===" +date -u +"UTC: %F %T" +echo "Log: $LOG" +echo +echo "WLAN_IF=$WLAN_IF AP=${AP_CIDR} SSID=${AP_SSID} UI=${UI_PORT}" +echo "ETH_IF=$ETH_IF FB=${ETH_FB_CIDR}" +echo + +# ---------- Preflight ---------- +if [[ ${EUID:-$(id -u)} -ne 0 ]]; then + echo "ERROR: Run as root: sudo bash $0" >&2 + exit 1 +fi + +# ---------- Packages ---------- +echo "[1/10] Install packages..." +apt-get update -y +apt-get install -y hostapd dnsmasq iw rfkill python3 network-manager iptables iproute2 curl + +echo "[2/10] Prefer iptables-legacy if available..." +if update-alternatives --list iptables >/dev/null 2>&1; then + update-alternatives --set iptables /usr/sbin/iptables-legacy >/dev/null 2>&1 || true +fi +if update-alternatives --list ip6tables >/dev/null 2>&1; then + update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy >/dev/null 2>&1 || true +fi + +echo "[3/10] Stop/disable stock services (we use our own units)..." +systemctl disable --now hostapd 2>/dev/null || true +systemctl disable --now dnsmasq 2>/dev/null || true + +# ---------- Paths ---------- +echo "[4/10] Write configs..." +mkdir -p /etc/iomatex /etc/hostapd /etc/dnsmasq.d /opt/iomatex-wifi-ui /usr/local/sbin + +backup_if_exists /etc/iomatex/failback.env +cat > /etc/iomatex/failback.env < /etc/hostapd/iomatex-ap.conf < /etc/dnsmasq.d/iomatex-ap.conf < AP IP +address=/#/${AP_IP} +EOF +chmod 0644 /etc/dnsmasq.d/iomatex-ap.conf + +backup_if_exists /etc/dnsmasq.d/iomatex-eth.conf +cat > /etc/dnsmasq.d/iomatex-eth.conf < /etc/systemd/system/iomatex-hostapd.service <<'EOF' +[Unit] +Description=IOMATEX hostapd (Wi-Fi AP) +After=network.target +Wants=network.target + +[Service] +Type=simple +ExecStart=/usr/sbin/hostapd -dd /etc/hostapd/iomatex-ap.conf +Restart=on-failure +RestartSec=2 + +[Install] +WantedBy=multi-user.target +EOF + +backup_if_exists /etc/systemd/system/iomatex-dnsmasq-ap.service +cat > /etc/systemd/system/iomatex-dnsmasq-ap.service <<'EOF' +[Unit] +Description=IOMATEX dnsmasq (AP DHCP/DNS) +After=network.target +Wants=network.target + +[Service] +Type=simple +ExecStart=/usr/sbin/dnsmasq --no-daemon --conf-file=/etc/dnsmasq.d/iomatex-ap.conf +Restart=on-failure +RestartSec=2 + +[Install] +WantedBy=multi-user.target +EOF + +backup_if_exists /etc/systemd/system/iomatex-dnsmasq-eth.service +cat > /etc/systemd/system/iomatex-dnsmasq-eth.service <<'EOF' +[Unit] +Description=IOMATEX dnsmasq (ETH DHCP-only) +After=network.target +Wants=network.target + +[Service] +Type=simple +ExecStart=/usr/sbin/dnsmasq --no-daemon --conf-file=/etc/dnsmasq.d/iomatex-eth.conf +Restart=on-failure +RestartSec=2 + +[Install] +WantedBy=multi-user.target +EOF + +# ---------- UI app ---------- +cat > /opt/iomatex-wifi-ui/app.py <<'PY' +#!/usr/bin/env python3 +import json, urllib.parse, subprocess +from http.server import BaseHTTPRequestHandler, HTTPServer + +def run(cmd): + p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + return p.returncode, (p.stdout or "").strip() + +HTML = """ + +IOMATEX Wi-Fi Setup + +

IOMATEX Wi-Fi Setup

+ +
+ Status +
Loading…
+ +
+ +
+ Connect to external Wi-Fi +
In AP/ETH mode scanning may be unavailable; enter SSID manually.
+ + +
+
+
+ + + +""" + +class H(BaseHTTPRequestHandler): + def address_string(self): + return self.client_address[0] + def log_message(self, fmt, *args): + return + def _send(self, code, body, ctype): + b = body.encode("utf-8") if isinstance(body, str) else body + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(b))) + self.end_headers() + self.wfile.write(b) + + def do_GET(self): + if self.path.startswith("/api/status"): + rc, out = run(["/usr/local/sbin/iomatex-failback-status"]) + self._send(200, json.dumps({"ok": rc == 0, "output": out}), "application/json") + return + self._send(200, HTML, "text/html; charset=utf-8") + + def do_POST(self): + if self.path.startswith("/api/connect"): + n = int(self.headers.get("Content-Length", "0")) + data = self.rfile.read(n).decode("utf-8", "ignore") + form = urllib.parse.parse_qs(data) + ssid = (form.get("ssid", [""])[0] or "").strip() + pw = (form.get("pass", [""])[0] or "") + if not ssid: + self._send(400, json.dumps({"ok": False, "output": "SSID required"}), "application/json") + return + rc, out = run(["/usr/local/sbin/iomatex-wifi-setup", ssid, pw]) + self._send(200, json.dumps({"ok": rc == 0, "rc": rc, "output": out}), "application/json") + return + self._send(404, "Not Found", "text/plain; charset=utf-8") + +def main(): + HTTPServer.allow_reuse_address = True + HTTPServer(("0.0.0.0", 18080), H).serve_forever() + +if __name__ == "__main__": + main() +PY +chmod 0755 /opt/iomatex-wifi-ui/app.py + +backup_if_exists /etc/systemd/system/iomatex-wifi-ui.service +cat > /etc/systemd/system/iomatex-wifi-ui.service <<'EOF' +[Unit] +Description=IOMATEX Wi-Fi Setup UI +After=network.target +Wants=network.target + +[Service] +Type=simple +ExecStart=/usr/bin/python3 /opt/iomatex-wifi-ui/app.py +Restart=on-failure +RestartSec=2 + +[Install] +WantedBy=multi-user.target +EOF + +# ---------- Control scripts ---------- +echo "[6/10] Control scripts..." + +# Captive iptables chain (no flushing PREROUTING) +cat > /usr/local/sbin/iomatex-iptables-captive <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/failback.env +CHAIN="IOMATEX_CAPTIVE" + +ensure_chain() { + iptables -t nat -L "$CHAIN" >/dev/null 2>&1 || iptables -t nat -N "$CHAIN" + iptables -t nat -C PREROUTING -j "$CHAIN" >/dev/null 2>&1 || iptables -t nat -I PREROUTING 1 -j "$CHAIN" +} + +enable() { + ensure_chain + iptables -t nat -C "$CHAIN" -i "$WLAN_IF" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} >/dev/null 2>&1 \ + || iptables -t nat -A "$CHAIN" -i "$WLAN_IF" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} +} + +disable() { + iptables -t nat -D "$CHAIN" -i "$WLAN_IF" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} >/dev/null 2>&1 || true +} + +case "${1:-}" in + on) enable ;; + off) disable ;; + *) echo "usage: $0 on|off" >&2; exit 2 ;; +esac +EOF +chmod 0755 /usr/local/sbin/iomatex-iptables-captive + +cat > /usr/local/sbin/iomatex-ap-up <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/failback.env + +rfkill unblock all >/dev/null 2>&1 || true + +if command -v nmcli >/dev/null 2>&1; then + nmcli dev disconnect "$WLAN_IF" >/dev/null 2>&1 || true + nmcli dev set "$WLAN_IF" managed no >/dev/null 2>&1 || true +fi + +ip link set "$WLAN_IF" up >/dev/null 2>&1 || true +ip addr flush dev "$WLAN_IF" >/dev/null 2>&1 || true +ip addr add "$AP_CIDR" dev "$WLAN_IF" + +systemctl start iomatex-dnsmasq-ap.service +systemctl start iomatex-hostapd.service +/usr/local/sbin/iomatex-iptables-captive on >/dev/null 2>&1 || true +EOF +chmod 0755 /usr/local/sbin/iomatex-ap-up + +cat > /usr/local/sbin/iomatex-ap-down <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/failback.env + +systemctl stop iomatex-hostapd.service 2>/dev/null || true +systemctl stop iomatex-dnsmasq-ap.service 2>/dev/null || true +/usr/local/sbin/iomatex-iptables-captive off >/dev/null 2>&1 || true + +ip addr flush dev "$WLAN_IF" 2>/dev/null || true + +if command -v nmcli >/dev/null 2>&1; then + nmcli dev set "$WLAN_IF" managed yes >/dev/null 2>&1 || true +fi +EOF +chmod 0755 /usr/local/sbin/iomatex-ap-down + +cat > /usr/local/sbin/iomatex-eth-fb-up <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/failback.env + +ip link set "$ETH_IF" up >/dev/null 2>&1 || true + +# Add fallback IP only if absent +if ! ip -4 -o addr show dev "$ETH_IF" 2>/dev/null | awk '{print $4}' | grep -q "^${ETH_FB_IP}/"; then + ip addr add "$ETH_FB_CIDR" dev "$ETH_IF" 2>/dev/null || true +fi + +systemctl start iomatex-dnsmasq-eth.service +EOF +chmod 0755 /usr/local/sbin/iomatex-eth-fb-up + +cat > /usr/local/sbin/iomatex-eth-fb-down <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/failback.env + +systemctl stop iomatex-dnsmasq-eth.service 2>/dev/null || true +ip addr del "$ETH_FB_CIDR" dev "$ETH_IF" 2>/dev/null || true +EOF +chmod 0755 /usr/local/sbin/iomatex-eth-fb-down + +cat > /usr/local/sbin/iomatex-wifi-setup <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/failback.env + +SSID_IN="${1:-}" +PASS_IN="${2:-}" + +[[ -n "$SSID_IN" ]] || { echo "ERROR: SSID required" >&2; exit 2; } +command -v nmcli >/dev/null 2>&1 || { echo "ERROR: nmcli not found" >&2; exit 3; } + +LOCK="/run/iomatex-wifi-setup.lock" +exec 9>"$LOCK" +flock -n 9 || { echo "ERROR: busy" >&2; exit 4; } + +sta_ok() { + nmcli -t -f DEVICE,STATE dev | grep -q "^${WLAN_IF}:connected$" || return 1 + ip -4 -o addr show dev "$WLAN_IF" 2>/dev/null | grep -q "inet " || return 1 + return 0 +} + +# Ensure AP is down to return wlan0 to NM +/usr/local/sbin/iomatex-ap-down >/dev/null 2>&1 || true + +nmcli dev set "$WLAN_IF" managed yes >/dev/null 2>&1 || true +ip addr flush dev "$WLAN_IF" >/dev/null 2>&1 || true +ip link set "$WLAN_IF" up >/dev/null 2>&1 || true + +CN="$(echo "$SSID_IN" | tr -cd "[:alnum:] ._-" | sed -E "s/[[:space:]]+/ /g" | cut -c1-64)" +[[ -n "$CN" ]] || CN="iomatex-wifi" + +nmcli con delete id "$CN" >/dev/null 2>&1 || true +nmcli con add type wifi ifname "$WLAN_IF" con-name "$CN" ssid "$SSID_IN" >/dev/null + +if [[ -n "$PASS_IN" ]]; then + nmcli con mod "$CN" wifi-sec.key-mgmt wpa-psk wifi-sec.psk "$PASS_IN" >/dev/null +else + nmcli con mod "$CN" wifi-sec.key-mgmt none >/dev/null 2>&1 || true +fi + +nmcli con mod "$CN" connection.autoconnect yes connection.autoconnect-priority 10 ipv4.method auto ipv6.method ignore >/dev/null +nmcli dev disconnect "$WLAN_IF" >/dev/null 2>&1 || true +nmcli con up id "$CN" >/dev/null 2>&1 || true + +sleep 10 + +if sta_ok; then + ip4="$(ip -4 -o addr show dev "$WLAN_IF" 2>/dev/null | awk '{print $4}' | head -n1 || true)" + { echo "WIFI_PROFILE=\"$CN\""; echo "WIFI_SSID=\"$SSID_IN\""; echo "WIFI_IP4=\"${ip4:-}\""; } > /etc/iomatex/wifi.env + chmod 0644 /etc/iomatex/wifi.env + echo "OK: STA connected (profile=$CN) IP=${ip4:-n/a}" + exit 0 +fi + +echo "ERROR: STA not connected / no IPv4" >&2 +exit 10 +EOF +chmod 0755 /usr/local/sbin/iomatex-wifi-setup + +cat > /usr/local/sbin/iomatex-failback-status <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/failback.env + +ap_active=0; systemctl is-active --quiet iomatex-hostapd.service && ap_active=1 +eth_dhcp=0; systemctl is-active --quiet iomatex-dnsmasq-eth.service && eth_dhcp=1 + +sta_connected=no +if command -v iw >/dev/null 2>&1; then + iw dev "$WLAN_IF" link 2>/dev/null | grep -q "^Connected to " && sta_connected=yes +fi + +wlan_ip4="$(ip -4 -o addr show dev "$WLAN_IF" 2>/dev/null | awk '{print $4}' | head -n1 || true)" +eth_ip4_list="$(ip -4 -o addr show dev "$ETH_IF" 2>/dev/null | awk '{print $4}' | tr '\n' ' ' || true)" +def_eth="$(ip -4 route show default dev "$ETH_IF" 2>/dev/null | head -n1 || true)" +state="$(cat /run/iomatex-failback.state 2>/dev/null || echo n/a)" + +echo "STATE=${state}" +echo +echo "WLAN_IF=${WLAN_IF}" +echo " AP_ACTIVE=${ap_active} (AP=${AP_CIDR})" +echo " STA_CONNECTED=${sta_connected}" +echo " IP4=${wlan_ip4:-none}" +echo +echo "ETH_IF=${ETH_IF}" +echo " DHCP_ACTIVE=${eth_dhcp} (FB=${ETH_FB_CIDR})" +echo " IP4_LIST=${eth_ip4_list:-none}" +echo " DEFAULT_ROUTE_ETH=${def_eth:-none}" +echo +echo "UI:" +echo " AP : http://${AP_IP}:${UI_PORT}" +echo " ETH : http://${ETH_FB_IP}:${UI_PORT}" +if [[ -n "${wlan_ip4:-}" ]]; then + echo " STA : http://${wlan_ip4%/*}:${UI_PORT}" +fi +EOF +chmod 0755 /usr/local/sbin/iomatex-failback-status + +cat > /usr/local/sbin/iomatex-ip <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/failback.env +echo "HOSTNAME=$(hostname -s)" +echo "---- eth0 ----"; ip -4 addr show dev "$ETH_IF" 2>/dev/null || true +echo "---- wlan0 ----"; ip -4 addr show dev "$WLAN_IF" 2>/dev/null || true +echo "---- default ----"; ip -4 route show default 2>/dev/null || true +echo "---- tips ----" +echo "AP mode : UI http://${AP_IP}:${UI_PORT} ; SSH -> ${AP_IP}" +echo "ETH mode: UI http://${ETH_FB_IP}:${UI_PORT} ; SSH -> ${ETH_FB_IP}" +EOF +chmod 0755 /usr/local/sbin/iomatex-ip + +# ---------- Watcher (NO-GRACE, prod-safe) ---------- +echo "[7/10] Watcher (enforces policy, no-grace)..." +cat > /usr/local/sbin/iomatex-failback-watch <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +. /etc/iomatex/failback.env + +STATE="/run/iomatex-failback.state" +LOCK="/run/iomatex-failback.lock" +exec 9>"$LOCK" +flock -n 9 || exit 0 + +eth_carrier_up() { + [[ -r "/sys/class/net/${ETH_IF}/carrier" ]] && [[ "$(cat "/sys/class/net/${ETH_IF}/carrier" 2>/dev/null || echo 0)" == "1" ]] +} + +eth_has_non_fallback_ipv4() { + ip -4 -o addr show dev "$ETH_IF" 2>/dev/null | awk '{print $4}' | grep -v -q "^${ETH_FB_IP}/" +} + +eth_has_default_route() { + ip -4 route show default dev "$ETH_IF" 2>/dev/null | grep -q "^default " +} + +# Production uplink ONLY if: non-fallback IPv4 + default route via eth0 +eth_prod_ok() { + eth_has_non_fallback_ipv4 && eth_has_default_route +} + +sta_ok() { + command -v nmcli >/dev/null 2>&1 || return 1 + nmcli -t -f DEVICE,STATE dev | grep -q "^${WLAN_IF}:connected$" || return 1 + ip -4 -o addr show dev "$WLAN_IF" 2>/dev/null | grep -q "inet " || return 1 + return 0 +} + +ap_is_up() { systemctl is-active --quiet iomatex-hostapd.service; } +eth_fb_is_up() { systemctl is-active --quiet iomatex-dnsmasq-eth.service; } +set_state() { echo "$1" > "$STATE"; } + +# 1) Production via eth0 -> no failbacks, AP off +if eth_prod_ok; then + eth_fb_is_up && /usr/local/sbin/iomatex-eth-fb-down || true + ap_is_up && /usr/local/sbin/iomatex-ap-down || true + set_state "prod_eth_ok" + exit 0 +fi + +# 2) If cable present and not production -> ETH failback ON, AP OFF +if eth_carrier_up; then + ap_is_up && /usr/local/sbin/iomatex-ap-down || true + eth_fb_is_up || /usr/local/sbin/iomatex-eth-fb-up + set_state "eth_failback" + exit 0 +fi + +# 3) No cable -> ETH failback OFF +eth_fb_is_up && /usr/local/sbin/iomatex-eth-fb-down || true + +# 4) No cable: if STA ok -> AP off +if sta_ok; then + ap_is_up && /usr/local/sbin/iomatex-ap-down || true + set_state "sta_ok" + exit 0 +fi + +# 5) No cable and no STA -> AP on +ap_is_up || /usr/local/sbin/iomatex-ap-up +set_state "ap_on_no_uplink" +EOF +chmod 0755 /usr/local/sbin/iomatex-failback-watch + +backup_if_exists /etc/systemd/system/iomatex-failback-watch.service +cat > /etc/systemd/system/iomatex-failback-watch.service <<'EOF' +[Unit] +Description=IOMATEX Failback Watch (prod-safe, no-grace) +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/iomatex-failback-watch +EOF + +backup_if_exists /etc/systemd/system/iomatex-failback-watch.timer +cat > /etc/systemd/system/iomatex-failback-watch.timer <<'EOF' +[Unit] +Description=IOMATEX Failback Watch timer + +[Timer] +OnBootSec=20 +OnUnitActiveSec=15 +AccuracySec=2 +Unit=iomatex-failback-watch.service + +[Install] +WantedBy=timers.target +EOF + +# ---------- Enable ---------- +echo "[8/10] Enable services..." +systemctl daemon-reload +systemctl enable --now iomatex-wifi-ui.service +systemctl enable --now iomatex-failback-watch.timer + +# ---------- Initial enforce ---------- +echo "[9/10] Initial enforce..." +/usr/local/sbin/iomatex-failback-watch || true + +# ---------- Quick self-test ---------- +echo "[10/10] Quick self-test (local UI)..." +for i in 1 2 3 4 5; do + ss -lnt 2>/dev/null | awk '{print $4}' | grep -qE "(:${UI_PORT})$" && break + sleep 1 +done +curl -m 2 -fsS "http://127.0.0.1:${UI_PORT}/api/status" >/dev/null 2>&1 || true + +echo +echo "=== INSTALL DONE ===" +echo "Wi-Fi AP:" +echo " SSID : ${AP_SSID}" +echo " PASS : ${AP_PASS}" +echo " IP : ${AP_IP}" +echo "ETH failback:" +echo " IP : ${ETH_FB_IP}" +echo "UI:" +echo " AP : http://${AP_IP}:${UI_PORT} (also http://${AP_IP} captive HTTP)" +echo " ETH : http://${ETH_FB_IP}:${UI_PORT}" +echo +echo "DIAG:" +echo " /usr/local/sbin/iomatex-failback-status" +echo " /usr/local/sbin/iomatex-ip" +echo " systemctl status iomatex-wifi-ui.service iomatex-failback-watch.timer --no-pager" +echo " journalctl -u iomatex-wifi-ui.service -u iomatex-failback-watch.service --no-pager -n 200" \ No newline at end of file diff --git a/tools/iomatex-install b/tools/iomatex-install new file mode 100755 index 0000000..2a135dd --- /dev/null +++ b/tools/iomatex-install @@ -0,0 +1,199 @@ +#!/usr/bin/env bash +set -euo pipefail + +BOOTSTRAP_VERSION="B-1.0.1" + +BUILD_BASE="${BUILD_BASE:-http://192.168.1.102:8088}" +CHANNEL="${CHANNEL:-stable}" + +WORK="/opt/iomatex-installer" +LOGDIR="/var/log/iomatex" +STATEDIR="/var/lib/iomatex/bootstrap" +BOOTLOG="$LOGDIR/bootstrap.log" + +mkdir -p "$WORK" "$LOGDIR" "$STATEDIR" +touch "$BOOTLOG" || true + +log() { + local msg="[$(date -u +'%F %T UTC')] $*" + echo "$msg" | tee -a "$BOOTLOG" +} + +need_root() { + if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then + echo "Run as root: sudo BUILD_BASE=... CHANNEL=... bash $0" + exit 1 + fi +} + +have_cmd(){ command -v "$1" >/dev/null 2>&1; } +strip_cr(){ tr -d '\r'; } + +fetch() { + local url="$1" out="$2" + mkdir -p "$(dirname "$out")" + log "GET $url" + curl -fsSL --retry 5 --retry-delay 1 --connect-timeout 5 --max-time 180 "$url" -o "$out" +} + +json_get_string() { + # expects "key": "value" + local key="$1" file="$2" + local line val + line="$(grep -oE "\"$key\"[[:space:]]*:[[:space:]]*\"[^\"]+\"" "$file" | head -n1 | strip_cr || true)" + val="$(printf "%s" "$line" | sed -E "s/.*\"$key\"[[:space:]]*:[[:space:]]*\"([^\"]+)\".*/\1/" | strip_cr)" + printf "%s" "$val" +} + +sha256_file(){ sha256sum "$1" | awk '{print $1}'; } + +verify_sums() { + local sums_file="$1" base_dir="$2" + log "Verify SHA256SUMS" + while IFS= read -r line; do + line="$(printf "%s" "$line" | strip_cr)" + [[ -z "$line" ]] && continue + [[ "$line" =~ ^# ]] && continue + + local expected relpath file actual + expected="$(echo "$line" | awk '{print $1}')" + relpath="$(echo "$line" | awk '{print $2}')" + [[ -z "${relpath:-}" ]] && continue + + file="$base_dir/$relpath" + [[ -f "$file" ]] || { log "ERROR missing: $relpath"; exit 2; } + + actual="$(sha256_file "$file")" + [[ "$actual" == "$expected" ]] || { + log "ERROR checksum mismatch: $relpath" + log " expected=$expected" + log " actual =$actual" + exit 3 + } + done < "$sums_file" +} + +manifest_steps() { + # outputs: id|type|file (simple parser; requires each field on its own line in manifest) + local mf="$1" + awk ' + BEGIN{inSteps=0} + /"steps"[[:space:]]*:[[:space:]]*\[/ {inSteps=1} + inSteps==1 { + if ($0 ~ /"id"[[:space:]]*:/) {gsub(/.*"id"[[:space:]]*:[[:space:]]*"/,""); gsub(/".*/,""); id=$0} + if ($0 ~ /"type"[[:space:]]*:/) {gsub(/.*"type"[[:space:]]*:[[:space:]]*"/,""); gsub(/".*/,""); type=$0} + if ($0 ~ /"file"[[:space:]]*:/) {gsub(/.*"file"[[:space:]]*:[[:space:]]*"/,""); gsub(/".*/,""); file=$0} + if ($0 ~ /}/ && id!="" && type!="" && file!="") {print id "|" type "|" file; id=""; type=""; file=""} + } + ' "$mf" | strip_cr +} + +step_done_file() { + local release="$1" step_id="$2" + echo "$STATEDIR/${release}__${step_id}.done" +} + +run_step_bash() { + local release="$1" step_id="$2" rel_dir="$3" script_rel="$4" + local donef steplog + donef="$(step_done_file "$release" "$step_id")" + steplog="$LOGDIR/${step_id}.log" + + if [[ -f "$donef" ]]; then + log "SKIP $step_id (already done: $(cat "$donef" 2>/dev/null || true))" + return 0 + fi + + [[ -f "$rel_dir/$script_rel" ]] || { log "ERROR step file missing: $script_rel"; exit 6; } + + chmod +x "$rel_dir/$script_rel" || true + log "RUN $step_id => $script_rel" + bash "$rel_dir/$script_rel" 2>&1 | tee -a "$steplog" + date -u +'%F %T UTC' > "$donef" + log "OK $step_id" +} + +main() { + need_root + log "=== IOMATEX bootstrap $BOOTSTRAP_VERSION start ===" + log "BUILD_BASE=$BUILD_BASE" + log "CHANNEL=$CHANNEL" + + if ! have_cmd curl; then + log "Installing curl/ca-certificates..." + apt-get update -y + apt-get install -y curl ca-certificates + fi + if ! have_cmd sha256sum; then + log "Installing coreutils..." + apt-get update -y + apt-get install -y coreutils + fi + + local latest="$WORK/latest.json" + fetch "$BUILD_BASE/releases/$CHANNEL/latest.json" "$latest" + + local release path + release="$(json_get_string release "$latest")" + path="$(json_get_string path "$latest")" + + [[ -n "${release:-}" && -n "${path:-}" ]] || { + log "ERROR: cannot parse latest.json" + cat "$latest" | cat -A + exit 4 + } + + log "Release=$release" + log "Path=$path" + + local rel_dir="$WORK/$release" + mkdir -p "$rel_dir" + + fetch "$BUILD_BASE/$path/manifest.json" "$rel_dir/manifest.json" + fetch "$BUILD_BASE/$path/SHA256SUMS" "$rel_dir/SHA256SUMS" + + log "Download payload..." + while IFS= read -r line; do + line="$(printf "%s" "$line" | strip_cr)" + [[ -z "$line" ]] && continue + [[ "$line" =~ ^# ]] && continue + file="$(echo "$line" | awk '{print $2}')" + [[ -n "${file:-}" ]] || continue + fetch "$BUILD_BASE/$path/$file" "$rel_dir/$file" + done < "$rel_dir/SHA256SUMS" + + verify_sums "$rel_dir/SHA256SUMS" "$rel_dir" + + log "Execute steps from manifest..." + local mf="$rel_dir/manifest.json" + local schema + schema="$(json_get_string schema "$mf")" + [[ -z "${schema:-}" ]] && schema="1" + [[ "$schema" == "1" ]] || { log "ERROR: unsupported manifest schema=$schema"; exit 5; } + + manifest_steps "$mf" | while IFS='|' read -r step_id step_type step_file; do + step_id="$(printf "%s" "$step_id" | strip_cr)" + step_type="$(printf "%s" "$step_type" | strip_cr)" + step_file="$(printf "%s" "$step_file" | strip_cr)" + [[ -z "${step_id:-}" ]] && continue + + if [[ "$step_type" == "bash" ]]; then + run_step_bash "$release" "$step_id" "$rel_dir" "$step_file" + else + log "ERROR: unsupported step type: $step_type (step $step_id)" + exit 7 + fi + done + + { + echo "release=$release" + echo "channel=$CHANNEL" + echo "build_base=$BUILD_BASE" + echo "bootstrap=$BOOTSTRAP_VERSION" + echo "installed_utc=$(date -u +'%F %T UTC')" + } > /etc/iomatex-release + + log "=== DONE: installed $release ===" +} + +main "$@" diff --git a/tools/iomatex-install_r b/tools/iomatex-install_r new file mode 100755 index 0000000..b1172d3 --- /dev/null +++ b/tools/iomatex-install_r @@ -0,0 +1,199 @@ +#!/usr/bin/env bash +set -euo pipefail + +BOOTSTRAP_VERSION="B-1.0.1" + +BUILD_BASE="${BUILD_BASE:-http://65.109.116.180}" +CHANNEL="${CHANNEL:-stable}" + +WORK="/opt/iomatex-installer" +LOGDIR="/var/log/iomatex" +STATEDIR="/var/lib/iomatex/bootstrap" +BOOTLOG="$LOGDIR/bootstrap.log" + +mkdir -p "$WORK" "$LOGDIR" "$STATEDIR" +touch "$BOOTLOG" || true + +log() { + local msg="[$(date -u +'%F %T UTC')] $*" + echo "$msg" | tee -a "$BOOTLOG" +} + +need_root() { + if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then + echo "Run as root: sudo BUILD_BASE=... CHANNEL=... bash $0" + exit 1 + fi +} + +have_cmd(){ command -v "$1" >/dev/null 2>&1; } +strip_cr(){ tr -d '\r'; } + +fetch() { + local url="$1" out="$2" + mkdir -p "$(dirname "$out")" + log "GET $url" + curl -fsSL --retry 5 --retry-delay 1 --connect-timeout 5 --max-time 180 "$url" -o "$out" +} + +json_get_string() { + # expects "key": "value" + local key="$1" file="$2" + local line val + line="$(grep -oE "\"$key\"[[:space:]]*:[[:space:]]*\"[^\"]+\"" "$file" | head -n1 | strip_cr || true)" + val="$(printf "%s" "$line" | sed -E "s/.*\"$key\"[[:space:]]*:[[:space:]]*\"([^\"]+)\".*/\1/" | strip_cr)" + printf "%s" "$val" +} + +sha256_file(){ sha256sum "$1" | awk '{print $1}'; } + +verify_sums() { + local sums_file="$1" base_dir="$2" + log "Verify SHA256SUMS" + while IFS= read -r line; do + line="$(printf "%s" "$line" | strip_cr)" + [[ -z "$line" ]] && continue + [[ "$line" =~ ^# ]] && continue + + local expected relpath file actual + expected="$(echo "$line" | awk '{print $1}')" + relpath="$(echo "$line" | awk '{print $2}')" + [[ -z "${relpath:-}" ]] && continue + + file="$base_dir/$relpath" + [[ -f "$file" ]] || { log "ERROR missing: $relpath"; exit 2; } + + actual="$(sha256_file "$file")" + [[ "$actual" == "$expected" ]] || { + log "ERROR checksum mismatch: $relpath" + log " expected=$expected" + log " actual =$actual" + exit 3 + } + done < "$sums_file" +} + +manifest_steps() { + # outputs: id|type|file (simple parser; requires each field on its own line in manifest) + local mf="$1" + awk ' + BEGIN{inSteps=0} + /"steps"[[:space:]]*:[[:space:]]*\[/ {inSteps=1} + inSteps==1 { + if ($0 ~ /"id"[[:space:]]*:/) {gsub(/.*"id"[[:space:]]*:[[:space:]]*"/,""); gsub(/".*/,""); id=$0} + if ($0 ~ /"type"[[:space:]]*:/) {gsub(/.*"type"[[:space:]]*:[[:space:]]*"/,""); gsub(/".*/,""); type=$0} + if ($0 ~ /"file"[[:space:]]*:/) {gsub(/.*"file"[[:space:]]*:[[:space:]]*"/,""); gsub(/".*/,""); file=$0} + if ($0 ~ /}/ && id!="" && type!="" && file!="") {print id "|" type "|" file; id=""; type=""; file=""} + } + ' "$mf" | strip_cr +} + +step_done_file() { + local release="$1" step_id="$2" + echo "$STATEDIR/${release}__${step_id}.done" +} + +run_step_bash() { + local release="$1" step_id="$2" rel_dir="$3" script_rel="$4" + local donef steplog + donef="$(step_done_file "$release" "$step_id")" + steplog="$LOGDIR/${step_id}.log" + + if [[ -f "$donef" ]]; then + log "SKIP $step_id (already done: $(cat "$donef" 2>/dev/null || true))" + return 0 + fi + + [[ -f "$rel_dir/$script_rel" ]] || { log "ERROR step file missing: $script_rel"; exit 6; } + + chmod +x "$rel_dir/$script_rel" || true + log "RUN $step_id => $script_rel" + bash "$rel_dir/$script_rel" 2>&1 | tee -a "$steplog" + date -u +'%F %T UTC' > "$donef" + log "OK $step_id" +} + +main() { + need_root + log "=== IOMATEX bootstrap $BOOTSTRAP_VERSION start ===" + log "BUILD_BASE=$BUILD_BASE" + log "CHANNEL=$CHANNEL" + + if ! have_cmd curl; then + log "Installing curl/ca-certificates..." + apt-get update -y + apt-get install -y curl ca-certificates + fi + if ! have_cmd sha256sum; then + log "Installing coreutils..." + apt-get update -y + apt-get install -y coreutils + fi + + local latest="$WORK/latest.json" + fetch "$BUILD_BASE/releases/$CHANNEL/latest.json" "$latest" + + local release path + release="$(json_get_string release "$latest")" + path="$(json_get_string path "$latest")" + + [[ -n "${release:-}" && -n "${path:-}" ]] || { + log "ERROR: cannot parse latest.json" + cat "$latest" | cat -A + exit 4 + } + + log "Release=$release" + log "Path=$path" + + local rel_dir="$WORK/$release" + mkdir -p "$rel_dir" + + fetch "$BUILD_BASE/$path/manifest.json" "$rel_dir/manifest.json" + fetch "$BUILD_BASE/$path/SHA256SUMS" "$rel_dir/SHA256SUMS" + + log "Download payload..." + while IFS= read -r line; do + line="$(printf "%s" "$line" | strip_cr)" + [[ -z "$line" ]] && continue + [[ "$line" =~ ^# ]] && continue + file="$(echo "$line" | awk '{print $2}')" + [[ -n "${file:-}" ]] || continue + fetch "$BUILD_BASE/$path/$file" "$rel_dir/$file" + done < "$rel_dir/SHA256SUMS" + + verify_sums "$rel_dir/SHA256SUMS" "$rel_dir" + + log "Execute steps from manifest..." + local mf="$rel_dir/manifest.json" + local schema + schema="$(json_get_string schema "$mf")" + [[ -z "${schema:-}" ]] && schema="1" + [[ "$schema" == "1" ]] || { log "ERROR: unsupported manifest schema=$schema"; exit 5; } + + manifest_steps "$mf" | while IFS='|' read -r step_id step_type step_file; do + step_id="$(printf "%s" "$step_id" | strip_cr)" + step_type="$(printf "%s" "$step_type" | strip_cr)" + step_file="$(printf "%s" "$step_file" | strip_cr)" + [[ -z "${step_id:-}" ]] && continue + + if [[ "$step_type" == "bash" ]]; then + run_step_bash "$release" "$step_id" "$rel_dir" "$step_file" + else + log "ERROR: unsupported step type: $step_type (step $step_id)" + exit 7 + fi + done + + { + echo "release=$release" + echo "channel=$CHANNEL" + echo "build_base=$BUILD_BASE" + echo "bootstrap=$BOOTSTRAP_VERSION" + echo "installed_utc=$(date -u +'%F %T UTC')" + } > /etc/iomatex-release + + log "=== DONE: installed $release ===" +} + +main "$@"