diff --git a/Source.list/source.sh b/Source.list/source.sh deleted file mode 100755 index 760f7cf..0000000 --- a/Source.list/source.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/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_branding/Desktop Wallpaper.png b/Stage_branding/Desktop Wallpaper.png deleted file mode 100755 index e1caf94..0000000 Binary files a/Stage_branding/Desktop Wallpaper.png and /dev/null differ diff --git a/Stage_branding/stage_branding.sh b/Stage_branding/stage_branding.sh deleted file mode 100755 index fb3bafe..0000000 --- a/Stage_branding/stage_branding.sh +++ /dev/null @@ -1,160 +0,0 @@ -#!/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 deleted file mode 100755 index aa12564..0000000 --- a/Stage_help/stage_help.sh +++ /dev/null @@ -1,394 +0,0 @@ -#!/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/local_installer.sh b/local_installer.sh new file mode 100755 index 0000000..d31103f --- /dev/null +++ b/local_installer.sh @@ -0,0 +1,420 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +SCRIPT_PATH="${BASH_SOURCE[0]}" +SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)" + +if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then + if command -v sudo >/dev/null 2>&1; then + exec sudo -E /bin/bash "$SCRIPT_PATH" "$@" + fi + echo "ERROR: root privileges are required. Run: sudo bash ./local_installer.sh" >&2 + exit 1 +fi + +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +export DEBIAN_FRONTEND="${DEBIAN_FRONTEND:-noninteractive}" + +LOG_FILE="${SCRIPT_DIR}/local_installer.log" +STATE_FILE="${SCRIPT_DIR}/local_installer.state" + +mkdir -p "$SCRIPT_DIR" +touch "$LOG_FILE" +touch "$STATE_FILE" +exec > >(tee -a "$LOG_FILE") 2>&1 + +CURRENT_STAGE="" +CURRENT_INSTALLER="" +CURRENT_INSTALLER_BASENAME="" + +SUCCESS_STAGES=() +SKIPPED_STAGES=() +FAILED_STAGES=() + +STAGE_ORDER=( + "stage_env" + "stage_wifi" + "stage_mqtt" + "stage_z2m" + "stage_reverse_tunnels" + "stage_ui" + "stage_itscreen" +) + +is_known_stage() { + local wanted="$1" + local stage + for stage in "${STAGE_ORDER[@]}"; do + [[ "$stage" == "$wanted" ]] && return 0 + done + return 1 +} + +log() { + printf '[%s] %s\n' "$(date -u +'%F %T UTC')" "$*" +} + +warn() { + log "WARN: $*" +} + +die() { + log "ERROR: $*" + exit 1 +} + +on_err() { + local rc="$1" + local line="$2" + if [[ -n "$CURRENT_STAGE" ]]; then + log "ERROR: unexpected failure in ${CURRENT_STAGE} at line ${line} (rc=${rc})" + else + log "ERROR: unexpected failure at line ${line} (rc=${rc})" + fi +} +trap 'on_err "$?" "$LINENO"' ERR + +usage() { + cat <<'EOF' +Usage: + sudo bash ./local_installer.sh + sudo bash ./local_installer.sh --reset-state + sudo bash ./local_installer.sh --from stage_mqtt + +Behavior: + - runs stage installers in fixed order + - skips missing stage directories + - skips stages without a detected installer + - resumes from local_installer.state by default + - stops on first stage failure + +Notes: + - reboot is not required immediately after stage_env + - final reboot is still recommended after full install so + LightDM autologin and reverse tunnels apply cleanly +EOF +} + +normalize_stage_key() { + local stage="$1" + printf '%s' "${stage//[^a-zA-Z0-9_]/_}" +} + +get_state_value() { + local key="$1" + if [[ ! -f "$STATE_FILE" ]]; then + return 0 + fi + awk -F= -v k="$key" '$1 == k { print substr($0, index($0, "=") + 1); found=1 } END { if (!found) exit 0 }' "$STATE_FILE" | tail -n1 +} + +set_state_value() { + local key="$1" + local value="$2" + local tmp + tmp="$(mktemp "${STATE_FILE}.tmp.XXXXXX")" + if [[ -f "$STATE_FILE" ]]; then + awk -F= -v k="$key" '$1 != k { print $0 }' "$STATE_FILE" >"$tmp" + fi + printf '%s=%s\n' "$key" "$value" >>"$tmp" + mv -f "$tmp" "$STATE_FILE" +} + +set_stage_status() { + local stage="$1" + local status="$2" + local key + key="STATUS_$(normalize_stage_key "$stage")" + set_state_value "$key" "$status" +} + +get_stage_status() { + local stage="$1" + local key + key="STATUS_$(normalize_stage_key "$stage")" + get_state_value "$key" +} + +reset_state() { + : >"$STATE_FILE" + log "State reset: $STATE_FILE" +} + +stage_candidates() { + local stage="$1" + case "$stage" in + stage_env) + printf '%s\n' "stage_env_install.sh" + ;; + stage_wifi) + printf '%s\n' "stage_wifi_install.sh" + ;; + stage_mqtt) + printf '%s\n' "stage_mqtt_install.sh" + ;; + stage_z2m) + printf '%s\n' "stage_z2m_install" + printf '%s\n' "stage_z2m_install.sh" + ;; + stage_reverse_tunnels) + printf '%s\n' "stage_reverse_tunnels_install.sh" + ;; + stage_ui) + printf '%s\n' "ui_installer.sh" + printf '%s\n' "stage_ui_install.sh" + printf '%s\n' "stage_display_addon.sh" + ;; + stage_itscreen) + printf '%s\n' "stage_itscreen_install.sh" + ;; + esac +} + +find_stage_installer() { + local stage="$1" + local stage_dir="${SCRIPT_DIR}/${stage}" + local candidate + local found=() + + [[ -d "$stage_dir" ]] || return 1 + + while IFS= read -r candidate; do + [[ -n "$candidate" ]] || continue + if [[ -f "${stage_dir}/${candidate}" ]]; then + printf '%s\n' "${stage_dir}/${candidate}" + return 0 + fi + done < <(stage_candidates "$stage") + + while IFS= read -r candidate; do + found+=("$candidate") + done < <( + find "$stage_dir" -maxdepth 1 -type f \ + \( -name '*_install.sh' -o -name '*_installer.sh' -o -name 'stage_*_install' -o -name 'stage_*_install.sh' \) \ + | sort + ) + + if [[ "${#found[@]}" -gt 0 ]]; then + printf '%s\n' "${found[0]}" + return 0 + fi + + return 1 +} + +record_summary_from_state() { + local stage + local status + SUCCESS_STAGES=() + SKIPPED_STAGES=() + FAILED_STAGES=() + for stage in "${STAGE_ORDER[@]}"; do + status="$(get_stage_status "$stage")" + case "$status" in + success) + SUCCESS_STAGES+=("$stage") + ;; + skipped*) + SKIPPED_STAGES+=("$stage") + ;; + failed) + FAILED_STAGES+=("$stage") + ;; + esac + done +} + +run_stage() { + local stage="$1" + local stage_dir="${SCRIPT_DIR}/${stage}" + local installer + local rc + + if [[ ! -d "$stage_dir" ]]; then + warn "SKIP: ${stage} not found" + set_stage_status "$stage" "skipped_stage_missing" + SKIPPED_STAGES+=("$stage") + return 0 + fi + + if ! installer="$(find_stage_installer "$stage")"; then + warn "SKIP: installer not found for ${stage}" + set_stage_status "$stage" "skipped_installer_missing" + SKIPPED_STAGES+=("$stage") + return 0 + fi + + CURRENT_STAGE="$stage" + CURRENT_INSTALLER="$installer" + CURRENT_INSTALLER_BASENAME="$(basename "$installer")" + + log "START: ${stage} -> ${CURRENT_INSTALLER_BASENAME}" + set_state_value "LAST_STAGE" "$stage" + set_state_value "LAST_INSTALLER" "$CURRENT_INSTALLER_BASENAME" + set_state_value "LAST_RESULT" "running" + + set +e + ( + cd "$stage_dir" + /bin/bash "./${CURRENT_INSTALLER_BASENAME}" + ) + rc=$? + set -e + + if [[ "$rc" -ne 0 ]]; then + set_stage_status "$stage" "failed" + set_state_value "LAST_RESULT" "failed" + FAILED_STAGES+=("$stage") + log "FAIL: ${stage} (installer=${CURRENT_INSTALLER_BASENAME}, rc=${rc})" + return "$rc" + fi + + set_stage_status "$stage" "success" + set_state_value "LAST_RESULT" "success" + SUCCESS_STAGES+=("$stage") + log "OK: ${stage}" + + CURRENT_STAGE="" + CURRENT_INSTALLER="" + CURRENT_INSTALLER_BASENAME="" + return 0 +} + +print_summary() { + local stage + local status + + echo + echo "============================================================" + echo "LOCAL INSTALLER SUMMARY" + echo "============================================================" + echo "Log file : ${LOG_FILE}" + echo "State file : ${STATE_FILE}" + echo + + echo "Successful stages:" + if [[ "${#SUCCESS_STAGES[@]}" -eq 0 ]]; then + echo " - none" + else + for stage in "${SUCCESS_STAGES[@]}"; do + status="$(get_stage_status "$stage")" + echo " - ${stage} (${status})" + done + fi + + echo + echo "Skipped stages:" + if [[ "${#SKIPPED_STAGES[@]}" -eq 0 ]]; then + echo " - none" + else + for stage in "${SKIPPED_STAGES[@]}"; do + status="$(get_stage_status "$stage")" + case "$status" in + skipped_stage_missing) + echo " - ${stage} (stage directory not found)" + ;; + skipped_installer_missing) + echo " - ${stage} (installer not found)" + ;; + *) + echo " - ${stage} (${status})" + ;; + esac + done + fi + + echo + echo "Failed stages:" + if [[ "${#FAILED_STAGES[@]}" -eq 0 ]]; then + echo " - none" + else + for stage in "${FAILED_STAGES[@]}"; do + echo " - ${stage}" + done + fi + + echo + echo "Post-install note:" + echo " - immediate reboot after stage_env is NOT required for the next stages" + echo " - final reboot is recommended after the full run" + echo " - reverse tunnels from stage_reverse_tunnels start automatically only after reboot" + echo "============================================================" +} + +FROM_STAGE="" +RESET_STATE=0 + +while [[ $# -gt 0 ]]; do + case "$1" in + --reset-state) + RESET_STATE=1 + shift + ;; + --from) + [[ $# -ge 2 ]] || die "--from requires a stage name" + FROM_STAGE="$2" + shift 2 + ;; + -h|--help) + usage + exit 0 + ;; + *) + die "Unknown argument: $1" + ;; + esac +done + +if [[ -n "$FROM_STAGE" ]] && ! is_known_stage "$FROM_STAGE"; then + die "Unknown stage for --from: ${FROM_STAGE}" +fi + +cd "$SCRIPT_DIR" + +if [[ "$RESET_STATE" -eq 1 ]]; then + reset_state +fi + +log "=== LOCAL INSTALLER START ===" +log "Project root: ${SCRIPT_DIR}" +log "Log file: ${LOG_FILE}" +log "State file: ${STATE_FILE}" + +STARTED=0 +RUN_FAILED=0 + +for stage in "${STAGE_ORDER[@]}"; do + status="$(get_stage_status "$stage")" + + if [[ -n "$FROM_STAGE" && "$STARTED" -eq 0 ]]; then + if [[ "$stage" == "$FROM_STAGE" ]]; then + STARTED=1 + else + continue + fi + else + STARTED=1 + fi + + if [[ -z "$FROM_STAGE" && "$status" == "success" ]]; then + log "RESUME: ${stage} already successful, skipping" + SUCCESS_STAGES+=("$stage") + continue + fi + + echo + echo ">>> RUNNING ${stage}" + if ! run_stage "$stage"; then + RUN_FAILED=1 + break + fi +done + +record_summary_from_state +print_summary + +if [[ "$RUN_FAILED" -ne 0 || "${#FAILED_STAGES[@]}" -gt 0 ]]; then + exit 1 +fi + +exit 0 diff --git a/stage_itscreen/itscreen b/stage_itscreen/itscreen new file mode 100644 index 0000000..f4193e9 Binary files /dev/null and b/stage_itscreen/itscreen differ diff --git a/stage_itscreen/itscreen:Zone.Identifier b/stage_itscreen/itscreen:Zone.Identifier new file mode 100644 index 0000000..d6c1ec6 Binary files /dev/null and b/stage_itscreen/itscreen:Zone.Identifier differ diff --git a/stage_ui/console_core/backend/app.py b/stage_ui/console_core/backend/app.py index c428073..cfc0b1c 100644 --- a/stage_ui/console_core/backend/app.py +++ b/stage_ui/console_core/backend/app.py @@ -11,6 +11,7 @@ import tempfile import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import urlparse +from itscreen_registration import get_registration_status, register_device, reset_registration APP_DIR = "/opt/iomatex-console" PUBLIC_DIR = os.path.join(APP_DIR, "public") @@ -26,6 +27,8 @@ DEFAULT_CONFIG = { _CACHE = {"expires_at": 0.0, "payload": None} _CPU_SAMPLE = {"total": None, "idle": None} _NET_SAMPLE = {} +_WIFI_SCAN_CACHE = {"expires_at": 0.0, "payload": None} +_WIFI_RESCAN_MIN_INTERVAL_SEC = 30.0 AP_ENV_PATH = "/etc/iomatex/ap.env" WIFI_ENV_PATH = "/etc/iomatex/wifi.env" AP_SYNC_SCRIPT = "/usr/local/sbin/iomatex-ap-sync-config" @@ -35,6 +38,7 @@ AP_DOWN_SCRIPT = "/usr/local/sbin/iomatex-ap-down" WIFI_STATUS_SCRIPT = "/usr/local/sbin/iomatex-wifi-status" WIFI_SETUP_SCRIPT = "/usr/local/sbin/iomatex-wifi-setup" AP_PASSWORD_RE = re.compile(r"^[a-z0-9]{8,}$") +DEFAULT_AP_UI_PORT = "80" CAPTIVE_PORTAL_PATH = "/portal" CAPTIVE_PORTAL_ALIASES = { "/captive-portal", @@ -225,7 +229,7 @@ def load_ap_state(): "factory_password": factory_password, "active_password": active_password, "iface": str(env.get("IFACE", "wlan0")).strip() or "wlan0", - "ui_port": str(env.get("UI_PORT", "18080")).strip() or "18080", + "ui_port": str(env.get("UI_PORT", DEFAULT_AP_UI_PORT)).strip() or DEFAULT_AP_UI_PORT, "service_state": hostapd_unit["active_state"], "service_installed": hostapd_unit["installed"], } @@ -800,17 +804,35 @@ def scan_wifi_networks(): if not nmcli_available(): return {"ok": False, "error": "nmcli not found", "networks": []} iface = get_primary_interface() - rescan_rc, _, rescan_stderr = run(["nmcli", "device", "wifi", "rescan", "ifname", iface], timeout=18) - if rescan_rc != 0: - if "not authorized" in rescan_stderr.lower(): - rescan_warning = "Wi-Fi rescan requires elevated privileges. Showing cached results." - elif "not found" in rescan_stderr.lower() or "no such device" in rescan_stderr.lower(): - return {"ok": False, "error": "Wi-Fi device is missing", "networks": []} + now = time.time() + cached = _WIFI_SCAN_CACHE.get("payload") + cache_expires_at = float(_WIFI_SCAN_CACHE.get("expires_at") or 0.0) + rescan_warning = "" + + try: + ap_state = load_ap_state() + except Exception: + ap_state = {"ap_enabled": False, "iface": iface} + + should_skip_rescan = False + if ap_state.get("ap_enabled") and (ap_state.get("iface") or iface) == iface: + should_skip_rescan = True + rescan_warning = "Access Point is active on this Wi-Fi interface. Showing cached scan results to avoid radio disruption." + elif cached and now < cache_expires_at: + should_skip_rescan = True + rescan_warning = "Wi-Fi scan cooldown is active. Showing cached results." + + if not should_skip_rescan: + rescan_rc, _, rescan_stderr = run(["nmcli", "device", "wifi", "rescan", "ifname", iface], timeout=18) + if rescan_rc != 0: + if "not authorized" in rescan_stderr.lower(): + rescan_warning = "Wi-Fi rescan requires elevated privileges. Showing cached results." + elif "not found" in rescan_stderr.lower() or "no such device" in rescan_stderr.lower(): + return {"ok": False, "error": "Wi-Fi device is missing", "networks": []} + else: + rescan_warning = rescan_stderr or "Wi-Fi rescan failed. Showing cached results." else: - rescan_warning = rescan_stderr or "Wi-Fi rescan failed. Showing cached results." - else: - rescan_warning = "" - time.sleep(2.0) + time.sleep(2.0) rc, stdout, stderr = run( ["nmcli", "-t", "-f", "IN-USE,SSID,SIGNAL,SECURITY", "device", "wifi", "list", "ifname", iface], timeout=18, @@ -869,6 +891,8 @@ def scan_wifi_networks(): response["warning"] = rescan_warning if not networks: response["message"] = "No Wi-Fi networks found" + _WIFI_SCAN_CACHE["payload"] = dict(response) + _WIFI_SCAN_CACHE["expires_at"] = now + _WIFI_RESCAN_MIN_INTERVAL_SEC return response @@ -1157,6 +1181,12 @@ class Handler(BaseHTTPRequestHandler): except Exception as exc: self.send_json({"ok": False, "error": str(exc), "networks": []}, code=500) return + if parsed.path == "/api/itscreen/registration": + try: + self.send_json(get_registration_status()) + except Exception as exc: + self.send_json({"ok": False, "error": str(exc)}, code=500) + return if parsed.path in ("/", "/index.html"): self.send_file(os.path.join(PUBLIC_DIR, "index.html"), "text/html; charset=utf-8") return @@ -1281,6 +1311,26 @@ class Handler(BaseHTTPRequestHandler): except Exception as exc: self.send_json({"ok": False, "error": str(exc)}, code=500) return + if parsed.path == "/api/itscreen/registration/register": + payload = self.read_json_body() + if payload is None: + self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400) + return + try: + self.send_json(register_device(str(payload.get("host", "")))) + except ValueError as exc: + self.send_json({"ok": False, "error": str(exc)}, code=400) + except RuntimeError as exc: + self.send_json({"ok": False, "error": str(exc)}, code=502) + except Exception as exc: + self.send_json({"ok": False, "error": str(exc)}, code=500) + return + if parsed.path == "/api/itscreen/registration/reset": + try: + self.send_json(reset_registration()) + except Exception as exc: + self.send_json({"ok": False, "error": str(exc)}, code=500) + return self.send_error(404) diff --git a/stage_ui/console_core/backend/itscreen_registration.py b/stage_ui/console_core/backend/itscreen_registration.py new file mode 100644 index 0000000..f31c3b0 --- /dev/null +++ b/stage_ui/console_core/backend/itscreen_registration.py @@ -0,0 +1,432 @@ +#!/usr/bin/env python3 +import json +import os +import queue +import re +import socket +import threading +import time +from urllib.parse import urlparse + +try: + import paho.mqtt.client as mqtt +except Exception: + mqtt = None + + +STATE_PATH = "/etc/iomatex/itscreen_registration.json" +MQTT_URL = os.environ.get("ITSCREEN_MQTT_URL", "mqtt://127.0.0.1:1883").strip() or "mqtt://127.0.0.1:1883" +LOGIN_PASSWORD = os.environ.get("ITSCREEN_DEVICE_PASSWORD", "eXXI0wkHBmNBnVbE").strip() or "eXXI0wkHBmNBnVbE" +DEFAULT_SERVER = "rest.uae.iomatex.com" +REGISTER_TIMEOUT_SEC = 25 +REPLY_TIMEOUT_SEC = 6 +HOST_RE = re.compile(r"^(?=.{1,253}$)(?!-)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.(?!-)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$") + + +def _device_hostname(): + host = "" + try: + host = os.uname().nodename + except Exception: + host = "" + host = (host or "").strip() + return host.split(".", 1)[0] if host else "unknown" + + +def _device_identity(): + device_id = _device_hostname() + return { + "device_id": device_id, + "device_name": device_id, + } + + +def validate_host(host): + value = str(host or "").strip().lower() + if not value: + raise ValueError("Invalid server host") + if "://" in value: + raise ValueError("Invalid server host") + if "/" in value: + raise ValueError("Invalid server host") + if value.endswith("."): + value = value[:-1] + if not HOST_RE.fullmatch(value): + raise ValueError("Invalid server host") + return value + + +def _default_state(): + identity = _device_identity() + return { + "host": DEFAULT_SERVER, + "username": "", + "password": "", + "token": "", + "organization": "", + "device_name": identity["device_name"], + "device_id": identity["device_id"], + "registered": False, + "logged": False, + "status": "idle", + "last_event": { + "action": "", + "operation": "", + "status": "", + "timestamp": "", + }, + } + + +def load_state(): + state = _default_state() + try: + with open(STATE_PATH, "r", encoding="utf-8") as fh: + loaded = json.load(fh) + if isinstance(loaded, dict): + state.update({k: v for k, v in loaded.items() if k in state}) + last_event = loaded.get("last_event") + if isinstance(last_event, dict): + state["last_event"].update(last_event) + except Exception: + pass + identity = _device_identity() + state["device_id"] = identity["device_id"] + state["device_name"] = state.get("device_name") or identity["device_name"] + state["host"] = state.get("host") or DEFAULT_SERVER + return state + + +def save_state(state): + os.makedirs(os.path.dirname(STATE_PATH), exist_ok=True) + safe = _default_state() + safe.update({ + "host": str(state.get("host", DEFAULT_SERVER) or DEFAULT_SERVER), + "username": str(state.get("username", "") or ""), + "password": str(state.get("password", "") or ""), + "token": str(state.get("token", "") or ""), + "organization": str(state.get("organization", "") or ""), + "device_name": str(state.get("device_name", "") or _device_identity()["device_name"]), + "device_id": str(state.get("device_id", "") or _device_identity()["device_id"]), + "registered": bool(state.get("registered", False)), + "logged": bool(state.get("logged", False)), + "status": str(state.get("status", "idle") or "idle"), + }) + last_event = state.get("last_event", {}) + if isinstance(last_event, dict): + safe["last_event"].update({ + "action": str(last_event.get("action", "") or ""), + "operation": str(last_event.get("operation", "") or ""), + "status": str(last_event.get("status", "") or ""), + "timestamp": str(last_event.get("timestamp", "") or ""), + }) + tmp_path = f"{STATE_PATH}.tmp" + with open(tmp_path, "w", encoding="utf-8") as fh: + json.dump(safe, fh, indent=2) + fh.write("\n") + os.replace(tmp_path, STATE_PATH) + + +def _parse_mqtt_url(raw_url): + parsed = urlparse(raw_url) + if parsed.scheme not in ("mqtt", "tcp"): + raise RuntimeError("Device settings service is unavailable") + host = parsed.hostname or "127.0.0.1" + port = parsed.port or 1883 + return host, port + + +def _topics(device_id): + base = f"it-screen/$devices/settings/{device_id}" + return {"sub": f"{base}/sub", "pub": f"{base}/pub"} + + +def _truncate_empty(value): + text = str(value or "").strip() + return text + + +def _extract_response_payload(response_text): + raw = str(response_text or "").strip() + if not raw: + return {} + try: + parsed = json.loads(raw) + return parsed if isinstance(parsed, dict) else {} + except Exception as exc: + raise RuntimeError(f"Could not parse backend response: {exc}") from exc + + +def _event_timestamp(): + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + + +def _extract_registration_fields(server_state, event_payload, persisted): + merged = dict(persisted) + sources = [server_state or {}, event_payload or {}] + for source in sources: + if not isinstance(source, dict): + continue + for key in ("host", "username", "password", "token", "organization"): + if source.get(key) not in (None, ""): + merged[key] = str(source.get(key)) + if source.get("device_name") not in (None, ""): + merged["device_name"] = str(source.get("device_name")) + elif source.get("name") not in (None, ""): + merged["device_name"] = str(source.get("name")) + if source.get("device_id") not in (None, ""): + merged["device_id"] = str(source.get("device_id")) + elif source.get("deviceId") not in (None, ""): + merged["device_id"] = str(source.get("deviceId")) + merged["device_name"] = merged.get("device_name") or _device_identity()["device_name"] + merged["device_id"] = _device_identity()["device_id"] + merged["registered"] = bool((server_state or {}).get("registered") or merged.get("token")) + merged["logged"] = bool((server_state or {}).get("logged")) + return merged + + +class MqttSettingsSession: + def __init__(self, device_id): + if mqtt is None: + raise RuntimeError("Device settings service is unavailable") + self.device_id = device_id + self.queue = queue.Queue() + self.connected = threading.Event() + self.error = None + self.topics = _topics(device_id) + self.client = mqtt.Client(client_id=f"console-core-{device_id}-{int(time.time() * 1000)}", clean_session=True) + self.client.on_connect = self._on_connect + self.client.on_message = self._on_message + self.client.on_disconnect = self._on_disconnect + + def _on_connect(self, client, userdata, flags, rc): + if rc != 0: + self.error = f"MQTT connect failed ({rc})" + return + result, _ = client.subscribe(self.topics["pub"], qos=0) + if result != mqtt.MQTT_ERR_SUCCESS: + self.error = "Device settings service is unavailable" + return + self.connected.set() + + def _on_disconnect(self, client, userdata, rc): + if rc not in (0, None) and not self.error: + self.error = "Device settings service is unavailable" + + def _on_message(self, client, userdata, msg): + raw = msg.payload.decode("utf-8", errors="ignore") + try: + payload = json.loads(raw) + except Exception: + payload = {"raw": raw} + self.queue.put(payload) + + def __enter__(self): + host, port = _parse_mqtt_url(MQTT_URL) + try: + self.client.connect(host, port, keepalive=30) + except Exception as exc: + raise RuntimeError("Device settings service is unavailable") from exc + self.client.loop_start() + if not self.connected.wait(5): + self.close() + raise RuntimeError(self.error or "Device settings service is unavailable") + return self + + def __exit__(self, exc_type, exc, tb): + self.close() + + def close(self): + try: + self.client.loop_stop() + except Exception: + pass + try: + self.client.disconnect() + except Exception: + pass + + def _drain(self): + while True: + try: + self.queue.get_nowait() + except queue.Empty: + return + + def publish(self, payload): + self._drain() + result = self.client.publish(self.topics["sub"], json.dumps(payload), qos=0, retain=False) + result.wait_for_publish(timeout=2) + if not result.is_published(): + raise RuntimeError("MQTT publish failed") + + def publish_and_wait(self, payload, predicate, timeout=REPLY_TIMEOUT_SEC): + self.publish(payload) + deadline = time.time() + timeout + while time.time() < deadline: + if self.error: + raise RuntimeError(self.error) + try: + candidate = self.queue.get(timeout=0.25) + except queue.Empty: + continue + if predicate(candidate): + return candidate + raise TimeoutError("No response from device") + + def login(self): + reply = self.publish_and_wait( + {"action": "login", "password": LOGIN_PASSWORD}, + lambda item: isinstance(item, dict) and item.get("action") == "login", + timeout=REPLY_TIMEOUT_SEC, + ) + if not reply.get("result"): + raise RuntimeError(reply.get("note") or reply.get("error") or "Login failed") + return reply + + def get_server_state(self): + return self.publish_and_wait( + {"action": "get", "category": "server"}, + lambda item: isinstance(item, dict) and item.get("category") == "server", + timeout=REPLY_TIMEOUT_SEC, + ) + + def set_server(self, host): + self.publish({"action": "set", "category": "server", "host": host}) + + def wait_registered_event(self, timeout=REGISTER_TIMEOUT_SEC): + deadline = time.time() + timeout + seen = set() + while time.time() < deadline: + if self.error: + raise RuntimeError(self.error) + try: + candidate = self.queue.get(timeout=0.25) + except queue.Empty: + continue + if not isinstance(candidate, dict): + continue + if candidate.get("action") != "registered" or candidate.get("operation") != "register": + continue + fingerprint = ( + candidate.get("action"), + candidate.get("operation"), + candidate.get("status"), + candidate.get("responseText"), + ) + if fingerprint in seen: + continue + seen.add(fingerprint) + return candidate + raise TimeoutError("Registration timeout") + + +def _build_public_status(state, error_text=""): + output = { + "ok": True, + "registered": bool(state.get("registered", False)), + "logged": bool(state.get("logged", False)), + "host": _truncate_empty(state.get("host")) or DEFAULT_SERVER, + "username": _truncate_empty(state.get("username")), + "password": _truncate_empty(state.get("password")), + "token": _truncate_empty(state.get("token")) or None, + "organization": _truncate_empty(state.get("organization")) or None, + "device_name": _truncate_empty(state.get("device_name")) or _device_identity()["device_name"], + "device_id": _device_identity()["device_id"], + "status": _truncate_empty(state.get("status")) or "idle", + "last_event": state.get("last_event", { + "action": "", + "operation": "", + "status": "", + "timestamp": "", + }), + } + if error_text: + output["error"] = error_text + return output + + +def get_registration_status(): + persisted = load_state() + state = dict(persisted) + try: + with MqttSettingsSession(state["device_id"]) as session: + session.login() + server_state = session.get_server_state() + state = _extract_registration_fields(server_state, {}, state) + state["logged"] = bool(server_state.get("logged")) + state["registered"] = bool(server_state.get("registered")) + state["status"] = "ready" if state["registered"] else "not_registered" + save_state(state) + return _build_public_status(state) + except Exception as exc: + state["status"] = "error" if persisted.get("status") != "registering" else persisted.get("status") + return _build_public_status(state, str(exc)) + + +def register_device(host): + validated_host = validate_host(host) + persisted = load_state() + working = dict(persisted) + working["host"] = validated_host + working["status"] = "registering" + save_state(working) + + try: + with MqttSettingsSession(working["device_id"]) as session: + session.login() + session.get_server_state() + session.set_server(validated_host) + event = session.wait_registered_event() + event_payload = _extract_response_payload(event.get("responseText")) + server_state = session.get_server_state() + merged = _extract_registration_fields(server_state, event_payload, working) + merged["host"] = validated_host + merged["status"] = "ready" if merged.get("registered") else "error" + merged["last_event"] = { + "action": str(event.get("action", "") or ""), + "operation": str(event.get("operation", "") or ""), + "status": str(event.get("status", "") or ""), + "timestamp": _event_timestamp(), + } + save_state(merged) + return { + "ok": True, + "status": "registered" if merged.get("registered") else "error", + "message": "Device successfully registered in cloud." if merged.get("registered") else "Cloud registration failed", + "data": _build_public_status(merged), + } + except TimeoutError as exc: + working["status"] = "error" + save_state(working) + raise RuntimeError(str(exc)) from exc + except Exception as exc: + working["status"] = "error" + save_state(working) + raise + + +def reset_registration(): + state = load_state() + state.update({ + "username": "", + "password": "", + "token": "", + "organization": "", + "registered": False, + "logged": False, + "status": "idle", + "last_event": { + "action": "reset", + "operation": "local", + "status": "warning", + "timestamp": _event_timestamp(), + }, + }) + save_state(state) + return { + "ok": True, + "message": "Cloud registration has been reset.", + "warning": "Local registration cache was cleared. Device-side unbind is not implemented in this runtime.", + "data": _build_public_status(state), + } diff --git a/stage_ui/console_core/frontend/console.css b/stage_ui/console_core/frontend/console.css index d634249..ca8275b 100644 --- a/stage_ui/console_core/frontend/console.css +++ b/stage_ui/console_core/frontend/console.css @@ -116,6 +116,30 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e } .tabContent{display:grid;gap:18px} .tabPanel{display:grid;gap:18px} +.toastStack{ + position:fixed; + right:18px; + bottom:18px; + display:grid; + gap:10px; + z-index:50; +} +.toast{ + min-width:260px; + max-width:360px; + padding:12px 14px; + border-radius:14px; + box-shadow:var(--shadow); + background:#ffffff; + border:1px solid var(--line); + color:var(--ink); + font-size:13px; + transition:opacity .2s ease,transform .2s ease; +} +.toast.success{border-color:rgba(14,122,83,.22);background:#f2faf6} +.toast.error{border-color:rgba(185,52,52,.22);background:#fff4f4} +.toast.warn{border-color:rgba(154,106,0,.24);background:#fff8ec} +.toast.is-leaving{opacity:0;transform:translateY(8px)} .sectionHead{display:flex;justify-content:space-between;gap:12px;align-items:flex-end;flex-wrap:wrap} .sectionHead h2{margin:0;font-size:22px} .sectionHead p{margin:0;color:var(--muted)} @@ -283,6 +307,40 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e } .field input:hover{border-color:#bfd0c8} .field input:focus-visible{border-color:var(--accent)} +.wrapValue{ + display:flex; + align-items:center; + gap:10px; + flex-wrap:wrap; + min-width:0; + overflow-wrap:anywhere; +} +.monoValue{ + font-family:ui-monospace,SFMono-Regular,Menlo,monospace; +} +.serverPicker{ + display:grid; + gap:10px; + margin-top:16px; +} +.choiceRow{ + display:grid; + grid-template-columns:auto 1fr; + gap:4px 10px; + align-items:start; + padding:12px 14px; + border:1px solid var(--line); + border-radius:14px; + background:#fbfcfb; +} +.choiceRow input{margin-top:3px} +.choiceRow span{font-weight:700} +.choiceRow small{grid-column:2;color:var(--muted);font-size:12px} +.actionColumn{ + display:grid; + gap:10px; + margin-top:16px; +} .passwordField{display:flex;gap:8px;align-items:center} .passwordField input{flex:1 1 auto} .toggleInlineBtn{ diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js index 2b42965..91c99cd 100644 --- a/stage_ui/console_core/frontend/console.js +++ b/stage_ui/console_core/frontend/console.js @@ -8,7 +8,8 @@ hostName: document.getElementById("hostName"), osLabel: document.getElementById("osLabel"), updatedAt: document.getElementById("updatedAt"), - content: document.getElementById("tabContent") + content: document.getElementById("tabContent"), + toastStack: document.getElementById("toastStack") }; const state = { @@ -16,7 +17,17 @@ status: null, health: null, network: null, - scan: { ok: true, networks: [], error: "", warning: "", message: "", loading: false, scannedAt: "", expanded: false }, + itscreen: { + loading: false, + busyAction: "", + data: null, + error: "", + serverMode: "uae", + customHost: "", + showPassword: false, + focused: false + }, + scan: { ok: true, networks: [], error: "", warning: "", message: "", loading: false, scannedAt: "", expanded: false, lastTriggeredAt: 0 }, networkForm: { ssid: "", password: "", @@ -95,6 +106,18 @@ return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())} (UTC)`; } + function showToast(kind, message) { + if (!nodes.toastStack || !message) return; + const toast = document.createElement("div"); + toast.className = `toast ${kind || "info"}`; + toast.textContent = message; + nodes.toastStack.appendChild(toast); + window.setTimeout(() => { + toast.classList.add("is-leaving"); + window.setTimeout(() => toast.remove(), 220); + }, 3600); + } + function signalQuality(signal) { const value = Number(signal); if (!Number.isFinite(value) || value <= 0) return { label: "Unknown", className: "is-weak", bars: 0, value: null }; @@ -128,6 +151,48 @@ `; } + function itscreenServerMode(host) { + const value = textValue(host, "").toLowerCase(); + if (value === "rest.uae.iomatex.com") return "uae"; + if (value === "rest.dev.it-screen.com") return "dev"; + return "custom"; + } + + function itscreenResolvedHost() { + if (state.itscreen.serverMode === "uae") return "rest.uae.iomatex.com"; + if (state.itscreen.serverMode === "dev") return "rest.dev.it-screen.com"; + return textValue(state.itscreen.customHost, ""); + } + + function itscreenHostValidationError() { + const host = itscreenResolvedHost().trim().toLowerCase(); + if (!host) return "Invalid server host"; + if (host.includes("://") || host.includes("/")) return "Invalid server host"; + if (!/^(?=.{1,253}$)(?!-)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.(?!-)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/.test(host)) { + return "Invalid server host"; + } + return ""; + } + + function itscreenStatusMeta(payload) { + if (!payload) return { label: "Loading", tone: "warn" }; + if (state.itscreen.busyAction === "register") return { label: "Registering", tone: "warn" }; + if (payload.status === "error" || state.itscreen.error) return { label: "Error", tone: "error" }; + if (payload.registered) return { label: "Registered", tone: "ok" }; + return { label: "Not registered", tone: "warn" }; + } + + function maskValue(value) { + return textValue(value, "") ? "••••••••" : "—"; + } + + function compactToken(value) { + const token = textValue(value, ""); + if (!token) return "—"; + if (token.length <= 20) return token; + return `${token.slice(0, 10)}…${token.slice(-6)}`; + } + function renderHealthOverviewPanel(metrics, temps) { const thermalRows = temps.length ? temps.map((item) => ({ label: item.name, value: item.label || "not available" })) @@ -524,6 +589,11 @@ return !!(state.activeTab === "network" && active && active.closest && active.closest("[data-network-form]")); } + function itscreenFormIsInteractive() { + const active = document.activeElement; + return !!(state.activeTab === "tscreen" && active && active.closest && active.closest("[data-itscreen-form]")); + } + function syncNetworkFormFromBackend() { const desired = (state.network && state.network.desired_profile) || {}; if (!state.networkForm.seeded) { @@ -745,25 +815,83 @@ } function renderTscreenTab() { + const payload = state.itscreen.data; + const busy = state.itscreen.busyAction; + const statusMeta = itscreenStatusMeta(payload); + const hostError = itscreenHostValidationError(); + const canRegister = !busy && !hostError; + const serverHost = itscreenResolvedHost() || "—"; + const lastEvent = payload && payload.last_event || {}; + + if (state.itscreen.loading && !payload) { + return `
Loading cloud registration status...
`; + } + return `
-
-

It-Screen

-

Foundation layout for the next major module.

-
- ${renderSimplePanel("Device Registration", [ - { label: "Status", value: "Ready for future backend contract" }, - { label: "Planned", value: "Registration, ownership, claims" } - ], "wideCard")} - ${renderSimplePanel("Runtime Role", [ - { label: "Planned", value: "Current role, device purpose, timers" }, - { label: "Interfaces", value: "Display, network, control surfaces" } - ], "wideCard")} - ${renderSimplePanel("Logs and Events", [ - { label: "Planned", value: "Operational logs and traceability" }, - { label: "Status", value: "Placeholder section prepared" } - ], "wideCard")} +
+
+
+

Cloud Registration Status

+
${esc(statusMeta.label)}
+
+
+ ${state.itscreen.error ? `` : ""} +
+
Status
${esc(statusMeta.label)}
+
Server
${esc(textValue(payload && payload.host, "—"))}
+
Device username
${esc(textValue(payload && payload.username, "—"))}
+
Device password
+
+ ${esc(state.itscreen.showPassword ? textValue(payload && payload.password, "—") : maskValue(payload && payload.password))} + +
+
Token
${esc(compactToken(payload && payload.token))}
+
Organization
${esc(textValue(payload && payload.organization, "—"))}
+
Device name
${esc(textValue(payload && payload.device_name, "—"))}
+
Device ID
${esc(textValue(payload && payload.device_id, "—"))}
+
+
+ +
+

Registration Server

+
+ + + +
+ ${state.itscreen.serverMode === "custom" ? ` + + ` : ""} +
Changing the server triggers device re-registration in cloud.
+
Resolved host: ${esc(serverHost)}
+
${esc(hostError)}
+
+ +
+

Actions

+
+ + + +
+
Reset current cloud registration?
+
The device will forget its current cloud binding and can be registered again.
+
+ +
+

Last registration event

+
+
Action
${esc(textValue(lastEvent.action, "—"))}
+
Operation
${esc(textValue(lastEvent.operation, "—"))}
+
Status
${esc(textValue(lastEvent.status, "—"))}
+
Timestamp
${esc(textValue(lastEvent.timestamp, "—"))}
+
+
`; @@ -924,6 +1052,32 @@ syncNetworkFormFromBackend(); } + function syncItscreenFormFromBackend() { + const payload = state.itscreen.data || {}; + if (!state.itscreen.focused && !state.itscreen.busyAction) { + state.itscreen.serverMode = itscreenServerMode(payload.host); + if (state.itscreen.serverMode === "custom") { + state.itscreen.customHost = textValue(payload.host, ""); + } else if (!state.itscreen.customHost) { + state.itscreen.customHost = textValue(payload.host, ""); + } + } + } + + async function loadItscreen() { + state.itscreen.loading = true; + state.itscreen.error = ""; + try { + state.itscreen.data = await fetchJson("/api/itscreen/registration", { cache: "no-store" }); + state.itscreen.error = state.itscreen.data && state.itscreen.data.error ? state.itscreen.data.error : ""; + syncItscreenFormFromBackend(); + } catch (error) { + state.itscreen.error = error.message || "Failed to load registration status"; + } finally { + state.itscreen.loading = false; + } + } + async function loadScan() { state.scan.loading = true; state.scan.error = ""; @@ -936,10 +1090,22 @@ warning: payload.warning || "", message: payload.message || "", loading: false, - scannedAt: new Date().toISOString() + scannedAt: new Date().toISOString(), + expanded: state.scan.expanded, + lastTriggeredAt: state.scan.lastTriggeredAt || 0 }; } catch (error) { - state.scan = { ok: false, error: error.message || "Failed to scan networks", warning: "", message: "", networks: [], loading: false, scannedAt: "" }; + state.scan = { + ok: false, + error: error.message || "Failed to scan networks", + warning: "", + message: "", + networks: [], + loading: false, + scannedAt: "", + expanded: state.scan.expanded, + lastTriggeredAt: state.scan.lastTriggeredAt || 0 + }; } } @@ -950,15 +1116,14 @@ await loadStatus(); if (state.activeTab === "network") { await loadNetwork(); - if (!preserveEditing || !networkFormIsInteractive()) { - await loadScan(); - } + } else if (state.activeTab === "tscreen") { + await loadItscreen(); } else if (state.activeTab === "health") { await loadHealth(); } - if (!(preserveEditing && state.activeTab === "network" && networkFormIsInteractive())) { + if (!(preserveEditing && state.activeTab === "network" && networkFormIsInteractive()) && !(preserveEditing && state.activeTab === "tscreen" && itscreenFormIsInteractive())) { renderActiveTab(); - } else { + } else if (state.activeTab === "network") { updateNetworkFormUi(); } } catch (error) { @@ -1095,8 +1260,18 @@ window.__scanNetworks = async function () { if (state.scan.loading) return; + const now = Date.now(); + const cooldownMs = 20000; + if (state.scan.lastTriggeredAt && now - state.scan.lastTriggeredAt < cooldownMs) { + const waitSec = Math.ceil((cooldownMs - (now - state.scan.lastTriggeredAt)) / 1000); + state.scan.warning = `Please wait ${waitSec}s before scanning again.`; + if (state.activeTab === "network") renderActiveTab(); + return; + } state.scan.expanded = true; state.scan.loading = true; + state.scan.warning = ""; + state.scan.lastTriggeredAt = now; renderActiveTab(); await loadScan(); if (state.activeTab === "network") renderActiveTab(); @@ -1143,6 +1318,105 @@ } }; + window.__toggleItscreenPassword = function () { + state.itscreen.showPassword = !state.itscreen.showPassword; + if (state.activeTab === "tscreen") renderActiveTab(); + }; + + window.__setItscreenServerMode = function (mode) { + state.itscreen.serverMode = mode; + if (mode !== "custom" && state.activeTab === "tscreen") renderActiveTab(); + if (mode === "custom" && !state.itscreen.customHost && state.itscreen.data) { + state.itscreen.customHost = textValue(state.itscreen.data.host, ""); + if (state.activeTab === "tscreen") renderActiveTab(); + } + }; + + window.__setItscreenCustomHost = function (value) { + state.itscreen.customHost = value; + const error = itscreenHostValidationError(); + const errorNode = document.getElementById("itscreenHostError"); + const resolvedNode = document.getElementById("itscreenResolvedHost"); + const registerBtn = document.getElementById("itscreenRegisterBtn"); + if (errorNode) { + errorNode.textContent = error || ""; + errorNode.hidden = !error; + } + if (resolvedNode) { + resolvedNode.innerHTML = `Resolved host: ${esc(itscreenResolvedHost() || "—")}`; + } + if (registerBtn) { + registerBtn.disabled = !!(state.itscreen.busyAction || error); + } + }; + + window.__setItscreenFocus = function (focused) { + state.itscreen.focused = !!focused; + }; + + window.__itscreenRefresh = async function () { + state.itscreen.busyAction = "refresh"; + if (state.activeTab === "tscreen") renderActiveTab(); + await loadItscreen(); + state.itscreen.busyAction = ""; + if (state.activeTab === "tscreen") renderActiveTab(); + }; + + window.__itscreenRegister = async function () { + const validationError = itscreenHostValidationError(); + if (validationError) { + state.itscreen.error = validationError; + if (state.activeTab === "tscreen") renderActiveTab(); + return; + } + state.itscreen.error = ""; + state.itscreen.busyAction = "register"; + if (state.activeTab === "tscreen") renderActiveTab(); + try { + const payload = await fetchJson("/api/itscreen/registration/register", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ host: itscreenResolvedHost() }) + }); + state.itscreen.data = payload.data || state.itscreen.data; + syncItscreenFormFromBackend(); + showToast("success", payload.message || "Device successfully registered in cloud."); + } catch (error) { + state.itscreen.error = error.message || "Cloud registration failed"; + showToast("error", state.itscreen.error); + } finally { + state.itscreen.busyAction = ""; + await loadItscreen(); + if (state.activeTab === "tscreen") renderActiveTab(); + } + }; + + window.__itscreenReset = async function () { + if (!window.confirm("Reset current cloud registration?\n\nThe device will forget its current cloud binding and can be registered again.")) return; + state.itscreen.error = ""; + state.itscreen.busyAction = "reset"; + if (state.activeTab === "tscreen") renderActiveTab(); + try { + const payload = await fetchJson("/api/itscreen/registration/reset", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: "{}" + }); + state.itscreen.data = payload.data || state.itscreen.data; + syncItscreenFormFromBackend(); + showToast(payload.warning ? "warn" : "success", payload.warning || payload.message || "Cloud registration has been reset."); + } catch (error) { + state.itscreen.error = error.message || "Failed to reset cloud registration"; + showToast("error", state.itscreen.error); + } finally { + state.itscreen.busyAction = ""; + await loadItscreen(); + if (state.activeTab === "tscreen") renderActiveTab(); + } + }; + nodes.tabs.forEach((button) => { button.addEventListener("click", async () => { const nextTab = button.dataset.tab; diff --git a/stage_ui/console_core/frontend/index.html b/stage_ui/console_core/frontend/index.html index 1656b25..0634f49 100644 --- a/stage_ui/console_core/frontend/index.html +++ b/stage_ui/console_core/frontend/index.html @@ -47,6 +47,7 @@
+
diff --git a/stage_ui/ui_installer.sh b/stage_ui/ui_installer.sh index 624f11a..2d62e93 100644 --- a/stage_ui/ui_installer.sh +++ b/stage_ui/ui_installer.sh @@ -30,6 +30,7 @@ PROVIDERS_DIR="${APP_DIR}/providers.d" FRONTEND_DIR="${APP_DIR}/frontend" SERVICE_NAME="iomatex-console.service" LEGACY_SERVICE_NAME="iomatex-webipc.service" +LEGACY_WIFI_UI_SERVICE_NAME="iomatex-wifi-ui.service" CFG_PATH="/etc/iomatex/console.json" SRC_LOGO="${LOGO_SOURCE:-$SCRIPT_DIR/iomatex_logo_source.png}" SRC_GBOX="${GBOX_SOURCE:-$SCRIPT_DIR/g-box.png}" @@ -39,6 +40,8 @@ ts="$(date +%s)" PREV_DIR="${APP_DIR}.prev.${ts}" LEGACY_APP_DIR="/opt/iomatex-process1-webipc" LEGACY_PREV_DIR="${LEGACY_APP_DIR}.prev.${ts}" +LEGACY_WIFI_UI_DIR="/opt/iomatex-wifi-ui" +LEGACY_WIFI_UI_PREV_DIR="${LEGACY_WIFI_UI_DIR}.prev.${ts}" STAGE_DIR="${APP_DIR}.staging.${ts}" STAGE_PUBLIC_DIR="${STAGE_DIR}/public" STAGE_BACKEND_DIR="${STAGE_DIR}/backend" @@ -197,6 +200,7 @@ get_active_ap_password() { echo "[0/8] Validate source tree" for path in \ "$SRC_ROOT/backend/app.py" \ + "$SRC_ROOT/backend/itscreen_registration.py" \ "$SRC_ROOT/frontend/index.html" \ "$SRC_ROOT/frontend/console.js" \ "$SRC_ROOT/frontend/console.css" \ @@ -209,7 +213,7 @@ done echo "[1/8] Ensure runtime packages exist" apt-get update -apt-get install -y python3 python3-pil network-manager iw hostapd dnsmasq rfkill iptables +apt-get install -y python3 python3-pil python3-paho-mqtt network-manager iw hostapd dnsmasq rfkill iptables if update-alternatives --list iptables >/dev/null 2>&1; then update-alternatives --set iptables /usr/sbin/iptables-legacy >/dev/null 2>&1 || true fi @@ -224,6 +228,7 @@ systemctl_try disable --now dnsmasq echo "[2/8] Stop previous service" stop_disable_reset_unit "${SERVICE_NAME}" stop_disable_reset_unit "${LEGACY_SERVICE_NAME}" +stop_disable_reset_unit "${LEGACY_WIFI_UI_SERVICE_NAME}" echo "[3/8] Prepare directories and preserve previous install" mkdir -p /etc/iomatex @@ -231,6 +236,11 @@ if [ -d "$LEGACY_APP_DIR" ]; then rm -rf "$LEGACY_PREV_DIR" mv "$LEGACY_APP_DIR" "$LEGACY_PREV_DIR" fi +if [ -d "$LEGACY_WIFI_UI_DIR" ]; then + rm -rf "$LEGACY_WIFI_UI_PREV_DIR" + mv "$LEGACY_WIFI_UI_DIR" "$LEGACY_WIFI_UI_PREV_DIR" +fi +remove_if_exists "/etc/systemd/system/${LEGACY_WIFI_UI_SERVICE_NAME}" rm -rf "$STAGE_DIR" mkdir -p "$STAGE_DIR" "$STAGE_PUBLIC_DIR" "$STAGE_BACKEND_DIR" "$STAGE_PROVIDERS_DIR" "$STAGE_FRONTEND_DIR" /etc/hostapd /etc/dnsmasq.d /usr/local/sbin @@ -308,6 +318,7 @@ install -m 0644 "$SRC_ROOT/frontend/console.css" "$STAGE_PUBLIC_DIR/console.css" copy_tree "$SRC_ROOT/providers" "$STAGE_PROVIDERS_DIR" rm -rf "$STAGE_PROVIDERS_DIR/__pycache__" "$STAGE_BACKEND_DIR/__pycache__" require_file "$STAGE_BACKEND_DIR/app.py" +require_file "$STAGE_BACKEND_DIR/itscreen_registration.py" require_file "$STAGE_FRONTEND_DIR/index.html" require_file "$STAGE_FRONTEND_DIR/console.js" require_file "$STAGE_FRONTEND_DIR/console.css" @@ -912,7 +923,7 @@ remove_if_exists /usr/local/sbin/iomatex-mdns-alias remove_if_exists /etc/systemd/system/iomatex-mdns-alias.service echo "[9/9] Validate and restart" -python3 -m py_compile "$STAGE_BACKEND_DIR/app.py" "$STAGE_PROVIDERS_DIR/00_core_services.py" +python3 -m py_compile "$STAGE_BACKEND_DIR/app.py" "$STAGE_BACKEND_DIR/itscreen_registration.py" "$STAGE_PROVIDERS_DIR/00_core_services.py" python3 -m py_compile /usr/local/sbin/iomatex-ap-resetd require_file "$STAGE_PUBLIC_DIR/index.html" require_file "$STAGE_PUBLIC_DIR/console.js" @@ -923,6 +934,7 @@ if [ -d "$APP_DIR" ]; then fi mv "$STAGE_DIR" "$APP_DIR" require_file "$BACKEND_DIR/app.py" +require_file "$BACKEND_DIR/itscreen_registration.py" require_file "$FRONTEND_DIR/index.html" require_file "$FRONTEND_DIR/console.js" require_file "$FRONTEND_DIR/console.css" @@ -973,3 +985,4 @@ echo "Public dir: ${PUBLIC_DIR}" echo "Config: ${CFG_PATH}" echo "Previous install backup: ${PREV_DIR}" echo "Legacy backup: ${LEGACY_PREV_DIR}" +echo "Legacy Wi-Fi UI backup: ${LEGACY_WIFI_UI_PREV_DIR}" diff --git a/stage_wifi/stage_wifi_install.sh b/stage_wifi/stage_wifi_install.sh index 4e919c4..89cf9ae 100644 --- a/stage_wifi/stage_wifi_install.sh +++ b/stage_wifi/stage_wifi_install.sh @@ -223,6 +223,13 @@ apt_update_if_needed() { fi } +apt_install_cmd() { + DEBIAN_FRONTEND=noninteractive apt-get -y \ + -o Dpkg::Options::="--force-confdef" \ + -o Dpkg::Options::="--force-confold" \ + "$@" +} + apt_install_missing() { local missing=() local pkg @@ -238,9 +245,13 @@ apt_install_missing() { return 0 fi + log "RUN: dpkg --configure -a || true" + dpkg --configure -a || true + log "RUN: DEBIAN_FRONTEND=noninteractive apt-get install -f -y ..." + apt_install_cmd install -f || true apt_update_if_needed - log "RUN: apt-get install -y ${missing[*]}" - apt-get install -y "${missing[@]}" + log "RUN: DEBIAN_FRONTEND=noninteractive apt-get install -y ${missing[*]}" + apt_install_cmd install "${missing[@]}" } HOSTNAME_SHORT="$(get_system_hostname)" diff --git a/tools/iomatex-install b/tools/iomatex-install deleted file mode 100755 index 2a135dd..0000000 --- a/tools/iomatex-install +++ /dev/null @@ -1,199 +0,0 @@ -#!/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 deleted file mode 100755 index b1172d3..0000000 --- a/tools/iomatex-install_r +++ /dev/null @@ -1,199 +0,0 @@ -#!/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 "$@"