Production stage v1.1.0

This commit is contained in:
Andrei Smaliak 2026-03-26 07:05:56 +04:00
parent 69aa5931ae
commit fe936cec87
6 changed files with 1449 additions and 460 deletions

View File

@ -1 +0,0 @@
8702730634:AAGkK557HdfTmIUEWa-Ai3oVyfmyj5tdqGc

View File

@ -1,10 +1,15 @@
#!/usr/bin/env bash
set -Eeuo pipefail
SCRIPT_PATH="${BASH_SOURCE[0]}"
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPT_PATH="${SCRIPT_DIR}/$(basename "${BASH_SOURCE[0]}")"
if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
ALLOW_NON_ROOT_WINDOW_MODE=0
if [[ "${1:-}" == "--open-post-reboot-window" ]]; then
ALLOW_NON_ROOT_WINDOW_MODE=1
fi
if [[ "${EUID:-$(id -u)}" -ne 0 && "$ALLOW_NON_ROOT_WINDOW_MODE" -ne 1 ]]; then
if command -v sudo >/dev/null 2>&1; then
exec sudo -E /bin/bash "$SCRIPT_PATH" "$@"
fi
@ -17,15 +22,23 @@ export DEBIAN_FRONTEND="${DEBIAN_FRONTEND:-noninteractive}"
LOG_FILE="${SCRIPT_DIR}/local_installer.log"
STATE_FILE="${SCRIPT_DIR}/local_installer.state"
POST_REBOOT_UNIT="iomatex-local-installer-post-reboot.service"
POST_REBOOT_UNIT_PATH="/etc/systemd/system/${POST_REBOOT_UNIT}"
POST_REBOOT_AUTOSTART="iomatex-local-installer-post-reboot.desktop"
POST_REBOOT_AUTOSTART_PATH="/etc/xdg/autostart/${POST_REBOOT_AUTOSTART}"
RESUME_POST_REBOOT=0
OPEN_POST_REBOOT_WINDOW=0
mkdir -p "$SCRIPT_DIR"
touch "$LOG_FILE"
touch "$STATE_FILE"
chmod 0644 "$LOG_FILE" "$STATE_FILE" 2>/dev/null || true
exec > >(tee -a "$LOG_FILE") 2>&1
CURRENT_STAGE=""
CURRENT_INSTALLER=""
CURRENT_INSTALLER_BASENAME=""
PROJECT_DIR="$SCRIPT_DIR"
SUCCESS_STAGES=()
SKIPPED_STAGES=()
@ -36,9 +49,9 @@ STAGE_ORDER=(
"stage_wifi"
"stage_mqtt"
"stage_z2m"
"stage_reverse_tunnels"
"stage_ui"
"stage_itscreen"
"stage_reverse_tunnels"
)
is_known_stage() {
@ -54,6 +67,10 @@ log() {
printf '[%s] %s\n' "$(date -u +'%F %T UTC')" "$*"
}
log_err() {
printf '[%s] %s\n' "$(date -u +'%F %T UTC')" "$*" >&2
}
warn() {
log "WARN: $*"
}
@ -78,18 +95,28 @@ usage() {
cat <<'EOF'
Usage:
sudo bash ./local_installer.sh
sudo bash ./local_installer.sh /path/to/Prod
sudo bash ./local_installer.sh /path/to/archive-with-Prod.tar.gz
sudo bash ./local_installer.sh --reset-state
sudo bash ./local_installer.sh --from stage_mqtt
sudo bash ./local_installer.sh --resume-post-reboot
bash ./local_installer.sh --open-post-reboot-window
Behavior:
- runs stage installers in fixed order
- optional source may be a Prod directory or an archive containing Prod/
- if source is omitted, installer looks for ./Prod or a single archive next to local_installer.sh
- skips missing stage directories
- skips stages without a detected installer
- resumes from local_installer.state by default
- forces reboot right after successful stage_env
- after reboot continues remaining stages via systemd
and shows live progress in lxterminal on DISPLAY=:0
- lxterminal is also started from desktop autologin as a fallback
- stops on first stage failure
Notes:
- reboot is not required immediately after stage_env
- tty1/getty/chvt are not used for installer UI
- final reboot is still recommended after full install so
LightDM autologin and reverse tunnels apply cleanly
EOF
@ -137,9 +164,299 @@ get_stage_status() {
reset_state() {
: >"$STATE_FILE"
systemctl disable "$POST_REBOOT_UNIT" >/dev/null 2>&1 || true
rm -f "$POST_REBOOT_AUTOSTART_PATH"
systemctl daemon-reload >/dev/null 2>&1 || true
log "State reset: $STATE_FILE"
}
next_stage_after() {
local current="$1"
local idx
for idx in "${!STAGE_ORDER[@]}"; do
if [[ "${STAGE_ORDER[$idx]}" == "$current" ]]; then
if (( idx + 1 < ${#STAGE_ORDER[@]} )); then
printf '%s\n' "${STAGE_ORDER[$((idx + 1))]}"
fi
return 0
fi
done
return 1
}
resolve_resume_stage() {
local stage
local started=0
local status
for stage in "${STAGE_ORDER[@]}"; do
if [[ "$started" -eq 0 ]]; then
[[ "$stage" == "stage_env" ]] && started=1
continue
fi
status="$(get_stage_status "$stage")"
if [[ "$status" != "success" ]]; then
printf '%s\n' "$stage"
return 0
fi
done
return 1
}
install_post_reboot_unit() {
cat >"$POST_REBOOT_UNIT_PATH" <<EOF
[Unit]
Description=IOMATEX local installer post-reboot continuation
After=display-manager.service
After=lightdm.service
Wants=display-manager.service
[Service]
Type=oneshot
WorkingDirectory=${SCRIPT_DIR}
ExecStart=/bin/bash ${SCRIPT_PATH} --resume-post-reboot
TimeoutStartSec=0
[Install]
WantedBy=graphical.target
EOF
systemctl daemon-reload
systemctl enable "$POST_REBOOT_UNIT" >/dev/null 2>&1 || true
log "Installed post-reboot unit: ${POST_REBOOT_UNIT_PATH}"
}
install_post_reboot_autostart() {
mkdir -p "$(dirname "$POST_REBOOT_AUTOSTART_PATH")"
cat >"$POST_REBOOT_AUTOSTART_PATH" <<EOF
[Desktop Entry]
Type=Application
Version=1.0
Name=IOMATEX Installer Post-Reboot Monitor
Comment=Opens installer progress window after GUI login
Exec=/bin/bash ${SCRIPT_PATH} --open-post-reboot-window
Terminal=false
NoDisplay=true
X-GNOME-Autostart-enabled=true
EOF
chmod 0644 "$POST_REBOOT_AUTOSTART_PATH"
log "Installed post-reboot GUI autostart: ${POST_REBOOT_AUTOSTART_PATH}"
}
cleanup_post_reboot_unit() {
set_state_value "POST_REBOOT_PENDING" "0"
set_state_value "NEXT_STAGE" ""
systemctl disable "$POST_REBOOT_UNIT" >/dev/null 2>&1 || true
rm -f "$POST_REBOOT_AUTOSTART_PATH"
systemctl daemon-reload >/dev/null 2>&1 || true
}
is_prod_root() {
local path="$1"
[[ -d "$path" && -d "$path/stage_env" && -f "$path/stage_env/stage_env_install.sh" ]]
}
resolve_abs_dir() {
local path="$1"
(cd "$path" && pwd)
}
resolve_abs_file() {
local path="$1"
local dir
local base
dir="$(cd "$(dirname "$path")" && pwd)"
base="$(basename "$path")"
printf '%s/%s\n' "$dir" "$base"
}
is_supported_archive() {
local path="$1"
case "${path,,}" in
*.tar|*.tar.gz|*.tgz|*.tar.xz|*.txz|*.zip) return 0 ;;
*) return 1 ;;
esac
}
resolve_prod_dir_from_path() {
local input="$1"
local abs_input=""
if [[ -d "$input" ]]; then
abs_input="$(resolve_abs_dir "$input")"
if is_prod_root "$abs_input"; then
printf '%s\n' "$abs_input"
return 0
fi
if is_prod_root "$abs_input/Prod"; then
printf '%s\n' "$abs_input/Prod"
return 0
fi
return 1
fi
[[ -f "$input" ]] || return 1
is_supported_archive "$input" || return 1
abs_input="$(resolve_abs_file "$input")"
local extract_root=""
extract_root="$(dirname "$abs_input")"
case "${abs_input,,}" in
*.zip)
command -v unzip >/dev/null 2>&1 || die "unzip is required to extract ${abs_input}"
log_err "Extracting archive ${abs_input} into ${extract_root}"
unzip -oq "$abs_input" -d "$extract_root"
;;
*)
command -v tar >/dev/null 2>&1 || die "tar is required to extract ${abs_input}"
log_err "Extracting archive ${abs_input} into ${extract_root}"
tar -xf "$abs_input" -C "$extract_root"
;;
esac
if is_prod_root "$extract_root/Prod"; then
printf '%s\n' "$extract_root/Prod"
return 0
fi
return 1
}
detect_default_source_path() {
local candidate=""
local archives=()
if is_prod_root "$SCRIPT_DIR"; then
printf '%s\n' "$SCRIPT_DIR"
return 0
fi
if is_prod_root "$SCRIPT_DIR/Prod"; then
printf '%s\n' "$SCRIPT_DIR/Prod"
return 0
fi
shopt -s nullglob
for candidate in \
"$SCRIPT_DIR"/*.tar \
"$SCRIPT_DIR"/*.tar.gz \
"$SCRIPT_DIR"/*.tgz \
"$SCRIPT_DIR"/*.tar.xz \
"$SCRIPT_DIR"/*.txz \
"$SCRIPT_DIR"/*.zip; do
[[ -f "$candidate" ]] || continue
archives+=("$candidate")
done
shopt -u nullglob
if [[ "${#archives[@]}" -eq 1 ]]; then
printf '%s\n' "${archives[0]}"
return 0
fi
return 1
}
spawn_log_terminal() {
local display_value="$1"
local log_path="$2"
export DISPLAY="${display_value}"
lxterminal --title="IOMATEX Installer" --command="/bin/bash -lc 'clear; printf \"\\n\\nIOMATEX ENV INSTALLATION IN PROGRESS\\n\"; printf \"====================================\\n\\n\"; printf \"Live log: %s\\n\\n\" \"$1\"; exec tail -n +1 -F \"$1\"' _ '$log_path'" >>"$LOG_FILE" 2>&1 &
}
find_gui_user() {
local gui_user=""
gui_user="$(who | awk '$2 ~ /^tty[0-9]+$/ {print $1; exit}')"
if [[ -n "$gui_user" ]]; then
printf '%s\n' "$gui_user"
return 0
fi
if command -v loginctl >/dev/null 2>&1; then
local session_id=""
while read -r session_id _; do
[[ -n "$session_id" ]] || continue
if [[ "$(loginctl show-session "$session_id" -p Active --value 2>/dev/null || true)" != "yes" ]]; then
continue
fi
if [[ "$(loginctl show-session "$session_id" -p Class --value 2>/dev/null || true)" != "user" ]]; then
continue
fi
gui_user="$(loginctl show-session "$session_id" -p Name --value 2>/dev/null || true)"
if [[ -n "$gui_user" ]]; then
printf '%s\n' "$gui_user"
return 0
fi
done < <(loginctl list-sessions --no-legend 2>/dev/null || true)
fi
return 1
}
launch_post_reboot_terminal() {
local gui_user=""
local xauthority_path=""
local attempt
local runuser_cmd=()
command -v lxterminal >/dev/null 2>&1 || {
warn "lxterminal is not installed; continuing without GUI installer window"
return 0
}
for attempt in $(seq 1 180); do
gui_user="$(find_gui_user || true)"
if [[ -n "$gui_user" ]]; then
xauthority_path="/home/${gui_user}/.Xauthority"
break
fi
sleep 2
done
if [[ -z "$gui_user" ]]; then
warn "GUI session on DISPLAY=:0 was not detected in time; continuing without GUI terminal window"
return 0
fi
log "Launching GUI installer terminal (lxterminal) as ${gui_user} on DISPLAY=:0"
runuser_cmd=(/usr/sbin/runuser -u "$gui_user" -- env DISPLAY=:0)
if [[ -f "$xauthority_path" ]]; then
runuser_cmd+=(XAUTHORITY="$xauthority_path")
else
warn "Xauthority file not found for ${gui_user}; trying GUI terminal launch without explicit XAUTHORITY"
fi
"${runuser_cmd[@]}" \
/bin/bash -lc '
command -v lxterminal >/dev/null 2>&1 || exit 0
exec lxterminal --title="IOMATEX Installer" --command="/bin/bash -lc '\''clear; printf \"\\n\\nIOMATEX ENV INSTALLATION IN PROGRESS\\n\"; printf \"====================================\\n\\n\"; printf \"Live log: %s\\n\\n\" \"$1\"; exec tail -n +1 -F \"$1\"'\'' _ '\''$1'\''"
' _ "$LOG_FILE" >>"$LOG_FILE" 2>&1 &
}
open_post_reboot_window_from_gui_session() {
if [[ "$(get_state_value "POST_REBOOT_PENDING")" != "1" ]]; then
log "No pending post-reboot continuation; GUI window is not needed"
return 0
fi
command -v lxterminal >/dev/null 2>&1 || {
warn "lxterminal is not installed; GUI monitor window cannot be opened"
return 0
}
if pgrep -af 'lxterminal.*IOMATEX Installer' >/dev/null 2>&1; then
log "Installer GUI terminal window is already running"
return 0
fi
export DISPLAY="${DISPLAY:-:0}"
log "Opening installer GUI terminal (lxterminal) from GUI session on DISPLAY=${DISPLAY}"
spawn_log_terminal "$DISPLAY" "$LOG_FILE"
}
stage_candidates() {
local stage="$1"
case "$stage" in
@ -172,7 +489,7 @@ stage_candidates() {
find_stage_installer() {
local stage="$1"
local stage_dir="${SCRIPT_DIR}/${stage}"
local stage_dir="${PROJECT_DIR}/${stage}"
local candidate
local found=()
@ -226,7 +543,7 @@ record_summary_from_state() {
run_stage() {
local stage="$1"
local stage_dir="${SCRIPT_DIR}/${stage}"
local stage_dir="${PROJECT_DIR}/${stage}"
local installer
local rc
@ -335,14 +652,16 @@ print_summary() {
echo
echo "Post-install note:"
echo " - immediate reboot after stage_env is NOT required for the next stages"
echo " - stage_env is always followed by an automatic reboot"
echo " - after reboot the installer resumes via systemd and opens lxterminal on DISPLAY=:0"
echo " - final reboot is recommended after the full run"
echo " - reverse tunnels from stage_reverse_tunnels start automatically only after reboot"
echo " - stage_reverse_tunnels is intentionally last because it requires manual completion"
echo "============================================================"
}
FROM_STAGE=""
RESET_STATE=0
SOURCE_PATH=""
while [[ $# -gt 0 ]]; do
case "$1" in
@ -355,12 +674,25 @@ while [[ $# -gt 0 ]]; do
FROM_STAGE="$2"
shift 2
;;
--resume-post-reboot)
RESUME_POST_REBOOT=1
shift
;;
--open-post-reboot-window)
OPEN_POST_REBOOT_WINDOW=1
shift
;;
-h|--help)
usage
exit 0
;;
*)
die "Unknown argument: $1"
if [[ -z "$SOURCE_PATH" ]]; then
SOURCE_PATH="$1"
shift
else
die "Unknown argument: $1"
fi
;;
esac
done
@ -376,10 +708,55 @@ if [[ "$RESET_STATE" -eq 1 ]]; then
fi
log "=== LOCAL INSTALLER START ==="
log "Project root: ${SCRIPT_DIR}"
log "Log file: ${LOG_FILE}"
log "State file: ${STATE_FILE}"
if [[ -z "$SOURCE_PATH" ]]; then
if [[ "$RESUME_POST_REBOOT" -eq 1 ]]; then
SOURCE_PATH="$(get_state_value "PROJECT_ROOT")"
fi
if [[ -z "$SOURCE_PATH" ]]; then
SOURCE_PATH="$(detect_default_source_path || true)"
fi
fi
[[ -n "$SOURCE_PATH" ]] || die "No Prod source found. Place local_installer.sh next to ./Prod or next to a single archive containing Prod/."
PROJECT_DIR="$(resolve_prod_dir_from_path "$SOURCE_PATH" || true)"
[[ -n "$PROJECT_DIR" ]] || die "Failed to resolve Prod from source: ${SOURCE_PATH}"
set_state_value "PROJECT_ROOT" "$PROJECT_DIR"
log "Project root: ${PROJECT_DIR}"
if [[ "$OPEN_POST_REBOOT_WINDOW" -eq 1 ]]; then
open_post_reboot_window_from_gui_session
exit 0
fi
if [[ "$RESUME_POST_REBOOT" -eq 1 ]]; then
if [[ "$(get_state_value "POST_REBOOT_PENDING")" != "1" ]]; then
die "Post-reboot continuation requested but no pending continuation state was found"
fi
FROM_STAGE="${FROM_STAGE:-$(resolve_resume_stage || true)}"
if [[ -z "$FROM_STAGE" ]]; then
log "No remaining stages after reboot; cleaning continuation state"
cleanup_post_reboot_unit
exit 0
fi
log "POST-REBOOT CONTINUATION: resuming from ${FROM_STAGE}"
echo
echo "============================================================"
echo "IOMATEX ENV INSTALLATION IN PROGRESS"
echo "============================================================"
echo "Continuation after reboot"
echo "Starting from: ${FROM_STAGE}"
echo "GUI output path: DISPLAY=:0 via lxterminal under active GUI user"
echo "============================================================"
echo
launch_post_reboot_terminal
fi
STARTED=0
RUN_FAILED=0
@ -408,6 +785,22 @@ for stage in "${STAGE_ORDER[@]}"; do
RUN_FAILED=1
break
fi
if [[ "$stage" == "stage_env" && "$RESUME_POST_REBOOT" -eq 0 && "$(get_stage_status "$stage")" == "success" ]]; then
NEXT_STAGE="$(next_stage_after "$stage" || true)"
set_state_value "POST_REBOOT_PENDING" "1"
set_state_value "NEXT_STAGE" "${NEXT_STAGE}"
set_state_value "LAST_RESULT" "reboot_pending"
install_post_reboot_unit
install_post_reboot_autostart
log "stage_env completed successfully; reboot is required before continuing"
log "Post-reboot continuation will resume from: ${NEXT_STAGE:-<none>}"
sync
sleep 2
systemctl reboot
exit 0
fi
done
record_summary_from_state
@ -417,4 +810,8 @@ if [[ "$RUN_FAILED" -ne 0 || "${#FAILED_STAGES[@]}" -gt 0 ]]; then
exit 1
fi
if [[ "$RESUME_POST_REBOOT" -eq 1 || "$(get_state_value "POST_REBOOT_PENDING")" == "1" ]]; then
cleanup_post_reboot_unit
fi
exit 0

View File

@ -334,6 +334,7 @@ apt_install_missing \
dos2unix \
logrotate \
rsyslog \
lxterminal \
network-manager \
policykit-1
@ -388,6 +389,7 @@ IOM_USER="iomatex"
IOM_PASS="iomatex" # default (must be changed on first login)
ITS_USER="itscreen"
Z2M_USER="zigbee2mqtt"
GUI_MIGRATION_CHANGED=0
ensure_user() {
local u="$1"
@ -428,6 +430,48 @@ 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
ensure_gui_home_state() {
local user="$1"
local home_dir=""
home_dir="$(getent passwd "$user" | cut -d: -f6 || true)"
[ -n "$home_dir" ] || return 0
install -d -m 0755 -o "$user" -g "$user" "$home_dir"
install -d -m 0700 -o "$user" -g "$user" "$home_dir/.config" "$home_dir/.cache" "$home_dir/.local"
install -d -m 0755 -o "$user" -g "$user" "$home_dir/Desktop" "$home_dir/Downloads"
for gui_file in .Xauthority .ICEauthority .dmrc; do
if [ -e "$home_dir/$gui_file" ]; then
chown "$user:$user" "$home_dir/$gui_file" 2>/dev/null || true
fi
done
}
configure_lightdm_autologin() {
[ -d /etc/lightdm ] || { log "LightDM not installed; skip GUI autologin migration"; return 0; }
mkdir -p /etc/lightdm/lightdm.conf.d
write_if_changed /etc/lightdm/lightdm.conf.d/90-iomatex-autologin.conf 0644 root root <<'EOF'
[Seat:*]
autologin-user=iomatex
autologin-user-timeout=0
EOF
if [ "$WRITE_CHANGED" -eq 1 ]; then
GUI_MIGRATION_CHANGED=1
fi
for lightdm_cfg in /etc/lightdm/lightdm.conf /etc/lightdm/lightdm.conf.d/*.conf; do
[ -f "$lightdm_cfg" ] || continue
if grep -qE '^[[:space:]]*autologin-user[[:space:]]*=[[:space:]]*youngfeel[[:space:]]*$' "$lightdm_cfg"; then
sed -i -E 's/^[[:space:]]*autologin-user[[:space:]]*=.*/autologin-user=iomatex/' "$lightdm_cfg"
GUI_MIGRATION_CHANGED=1
log "Updated LightDM autologin user in ${lightdm_cfg}: youngfeel -> iomatex"
fi
done
}
ensure_gui_home_state "$IOM_USER"
configure_lightdm_autologin
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
@ -519,9 +563,6 @@ Policy:
- pam_unix obscure: OFF
Cockpit : https://${IP_MAIN}:9090
Wi-Fi:
- Use command: sudo nmtui (manage Wi-Fi networks)
======================================================
EOF
chmod 0644 /etc/issue.cockpit
@ -539,251 +580,8 @@ cat >/etc/motd <<EOF
======================================================
Cockpit: https://${IP_MAIN}:9090
SECURITY: Change admin password (sudo iomatex-passwd)
Wi-Fi: sudo nmtui
EOF
# -------------------------
# Step 10.5: Wi-Fi industrial hardening (AE region + disable P2P + prefer wlan0 for client Wi-Fi)
# -------------------------
step "Wi-Fi hardening: set region AE + disable P2P + keep p2p0 out of NetworkManager"
apt_install_missing iw wireless-regdb || true
if command -v iw >/dev/null 2>&1; then
iw reg set AE || true
fi
if [ -e /sys/class/net/p2p0 ]; then
log "Detected kernel-created P2P interface: p2p0"
else
log "P2P interface p2p0 not present at install time (policy will still be enforced)"
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
for legacy_nm_cfg in \
/etc/NetworkManager/conf.d/10-iomatex-main.conf \
/etc/NetworkManager/conf.d/20-iomatex-disable-p2p.conf \
/etc/NetworkManager/conf.d/99-iomatex-wifi.conf
do
if [ -f "$legacy_nm_cfg" ]; then
rm -f "$legacy_nm_cfg"
NM_CFG_CHANGED=1
log "Removed legacy NetworkManager Wi-Fi policy: ${legacy_nm_cfg}"
fi
done
write_if_changed /etc/NetworkManager/conf.d/10-iomatex-disable-p2p.conf 0644 root root <<'EOF'
[main]
plugins=keyfile
[keyfile]
unmanaged-devices=interface-name:p2p0;interface-name:p2p-dev-p2p0;interface-name:p2p-dev-wlan0
[device]
wifi.scan-rand-mac-address=no
[connection]
wifi.powersave=2
EOF
if [ "$WRITE_CHANGED" -eq 1 ]; then
NM_CFG_CHANGED=1
log "Updated NetworkManager Wi-Fi baseline policy: /etc/NetworkManager/conf.d/10-iomatex-disable-p2p.conf"
else
log "NetworkManager Wi-Fi baseline policy already configured"
fi
WPA_CFG_CHANGED=0
WPA_CFGS=()
[ -f /etc/wpa_supplicant.conf ] && WPA_CFGS+=(/etc/wpa_supplicant.conf)
[ -f /etc/wpa_supplicant/wpa_supplicant.conf ] && WPA_CFGS+=(/etc/wpa_supplicant/wpa_supplicant.conf)
if [ "${#WPA_CFGS[@]}" -eq 0 ]; then
WPA_CFGS+=(/etc/wpa_supplicant.conf)
fi
for WPA_CFG in "${WPA_CFGS[@]}"; do
tmp_wpa="$(mktemp)"
if [ -f "$WPA_CFG" ]; then
awk '
BEGIN { done=0 }
/^[[:space:]]*p2p_disabled[[:space:]]*=/ {
if (!done) {
print "p2p_disabled=1"
done=1
}
next
}
{ print }
END {
if (!done) {
print "p2p_disabled=1"
}
}
' "$WPA_CFG" >"$tmp_wpa"
else
printf 'p2p_disabled=1\n' >"$tmp_wpa"
fi
if [ -f "$WPA_CFG" ] && cmp -s "$tmp_wpa" "$WPA_CFG"; then
rm -f "$tmp_wpa"
log "wpa_supplicant P2P disable already configured: ${WPA_CFG}"
else
install -D -o root -g root -m 0644 "$tmp_wpa" "$WPA_CFG"
rm -f "$tmp_wpa"
WPA_CFG_CHANGED=1
log "Updated wpa_supplicant P2P disable policy: ${WPA_CFG}"
fi
done
PROFILE_CFG_CHANGED=0
PROFILE_FIX_COUNT=0
shopt -s nullglob
for nm_profile in /etc/NetworkManager/system-connections/*.nmconnection; do
if grep -Eq '^[[:space:]]*interface-name[[:space:]]*=[[:space:]]*p2p0[[:space:]]*$' "$nm_profile"; then
tmp_profile="$(mktemp)"
awk '
/^[[:space:]]*interface-name[[:space:]]*=[[:space:]]*p2p0[[:space:]]*$/ { next }
{ print }
' "$nm_profile" >"$tmp_profile"
if ! cmp -s "$tmp_profile" "$nm_profile"; then
backup_if_exists "$nm_profile"
install -o root -g root -m 0600 "$tmp_profile" "$nm_profile"
PROFILE_CFG_CHANGED=1
PROFILE_FIX_COUNT=$((PROFILE_FIX_COUNT+1))
log "Removed interface-name=p2p0 from NetworkManager profile: $(basename "$nm_profile")"
fi
rm -f "$tmp_profile"
fi
done
shopt -u nullglob
if [ "$PROFILE_FIX_COUNT" -eq 0 ]; then
log "No NetworkManager profiles pinned to p2p0 were found"
else
log "Fixed NetworkManager profiles pinned to p2p0: ${PROFILE_FIX_COUNT}"
fi
if [ "$NM_CFG_CHANGED" -eq 1 ] || [ "$WPA_CFG_CHANGED" -eq 1 ] || [ "$PROFILE_CFG_CHANGED" -eq 1 ]; then
soft_run "Restart NetworkManager" 30 /bin/systemctl restart NetworkManager
else
log "NetworkManager restart not required for P2P policy"
fi
# -------------------------
# Step 10.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 10.7: Wi-Fi quiet-state (disable radio + block rfkill + keep wlan0/p2p0 down)
# -------------------------
step "Wi-Fi quiet-state: radio off + rfkill block + wlan0/p2p0 down"
write_if_changed /usr/local/sbin/iomatex-wifi-quiet 0755 <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
WIFI_IFACE="${1:-wlan0}"
P2P_IFACE="${2:-p2p0}"
if command -v nmcli >/dev/null 2>&1; then
nmcli device disconnect "$WIFI_IFACE" >/dev/null 2>&1 || true
nmcli radio wifi off >/dev/null 2>&1 || true
fi
rfkill block wifi >/dev/null 2>&1 || true
ip link set "$WIFI_IFACE" down >/dev/null 2>&1 || true
ip link set "$P2P_IFACE" down >/dev/null 2>&1 || true
EOF
WIFI_QUIET_UNIT_CHANGED=0
write_if_changed /etc/systemd/system/iomatex-wifi-quiet.service 0644 <<'EOF'
[Unit]
Description=IOMATEX Wi-Fi quiet-state enforcement
After=NetworkManager.service
Wants=NetworkManager.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/iomatex-wifi-quiet
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
EOF
if [ "$WRITE_CHANGED" -eq 1 ]; then
WIFI_QUIET_UNIT_CHANGED=1
fi
if [ "$WIFI_QUIET_UNIT_CHANGED" -eq 1 ]; then
soft_run "systemd daemon-reload (wifi quiet unit changed)" 20 /bin/systemctl daemon-reload
fi
soft_run "Enable iomatex-wifi-quiet.service" 20 /bin/systemctl enable iomatex-wifi-quiet.service
soft_run "Apply Wi-Fi quiet-state now" 20 /usr/local/sbin/iomatex-wifi-quiet
log "--- WIFI QUIET-STATE AFTER ---"
nmcli -f DEVICE,TYPE,STATE,CONNECTION dev >>"$LOG" 2>&1 || true
nmcli radio all >>"$LOG" 2>&1 || true
rfkill list >>"$LOG" 2>&1 || true
# -------------------------
# Step 11: /userdata usage (SAFE cold-boot)
# - NO bind-mount /var/log
@ -911,20 +709,6 @@ if [ "$WRITE_CHANGED" -eq 1 ]; then
RSYSLOG_ROTATE_CHANGED=1
fi
NM_LOGGING_CHANGED=0
mkdir -p /etc/NetworkManager/conf.d
write_if_changed /etc/NetworkManager/conf.d/logging.conf 0644 root root <<'EOF'
[logging]
level=INFO
domains=DEFAULT
EOF
if [ "$WRITE_CHANGED" -eq 1 ]; then
NM_LOGGING_CHANGED=1
fi
if [ "$NM_LOGGING_CHANGED" -eq 1 ]; then
soft_run "Restart NetworkManager (logging baseline)" 30 /bin/systemctl restart NetworkManager
fi
MOSQ_LOG_CFG_CHANGED=0
mkdir -p /etc/mosquitto/conf.d /var/log/mosquitto
touch /var/log/mosquitto/mosquitto.log
@ -1079,10 +863,10 @@ echo " - youngfeel (hardened/disabled if existed)"
echo
echo " Password policy : minlen=8 (NO dictionary), pam_unix obscure OFF"
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
if [ "$GUI_MIGRATION_CHANGED" -eq 1 ]; then
echo " GUI session : LightDM autologin switched to iomatex (reboot or lightdm restart required)"
echo
fi
echo " Userdata usage (cold-boot safe):"
echo " - swap on /userdata via systemd oneshot (no fstab)"
echo " - generic userdata log root at /userdata/logs/iomatex"

View File

@ -361,11 +361,21 @@ def build_captive_portal_html():
def ap_status_card():
status = load_ap_state()
script_status = parse_wifi_status_script()
installed = status["service_installed"] or file_exists(AP_ENV_PATH)
configured = file_exists(AP_SYNC_SCRIPT)
active = bool(status["ap_enabled"])
state = "active" if active else "inactive"
status_text = "AP enabled" if active else "AP disabled"
warnings = []
if script_status.get("DRIVER_UNAVAILABLE") == "yes":
state = "degraded"
status_text = "AP unavailable: Wi-Fi driver not loaded"
warnings.append("RTL8723DS driver is unloaded. Automatic Wi-Fi restore is disabled on this platform.")
elif script_status.get("DRIVER_DEGRADED") == "yes":
state = "degraded"
status_text = "AP unavailable: Wi-Fi driver degraded"
warnings.append("RTL8723DS degraded state detected. Automatic recovery is intentionally limited.")
return {
"id": "access_point",
"title": "Access Point",
@ -381,7 +391,7 @@ def ap_status_card():
],
"ap_status": public_ap_status(),
"errors": [],
"warnings": [],
"warnings": warnings,
}
@ -810,6 +820,12 @@ def get_network_summary():
script_status = parse_wifi_status_script()
current_ssid = get_active_ssid(iface)
wifi_summary = summarize_interface(iface, "wifi")
if script_status.get("DRIVER_UNAVAILABLE") == "yes" and not wifi_summary.get("present"):
wifi_summary["status"] = "driver-unavailable"
wifi_summary["status_text"] = "Wi-Fi driver unavailable"
elif script_status.get("DRIVER_DEGRADED") == "yes":
wifi_summary["status"] = "driver-degraded"
wifi_summary["status_text"] = "Wi-Fi driver degraded"
wifi_summary["ssid"] = current_ssid or profile["ssid"]
eth_summary = summarize_interface("eth0", "ethernet")
try:

View File

@ -0,0 +1,595 @@
#!/usr/bin/env bash
set -u
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
SCRIPT_NAME="$(basename "$0")"
LOG_FILE_DEFAULT="/var/log/iomatex-postinstall-selftest.log"
LOG_FILE="${LOG_FILE:-$LOG_FILE_DEFAULT}"
START_TS="$(date -u +'%F %T UTC')"
HOSTNAME_SHORT="$(hostname -s 2>/dev/null || hostname 2>/dev/null || echo unknown)"
PASS_COUNT=0
WARN_COUNT=0
FAIL_COUNT=0
TEST_COUNT=0
FAIL_ITEMS=()
WARN_ITEMS=()
mkdir -p "$(dirname "$LOG_FILE")" >/dev/null 2>&1 || true
touch "$LOG_FILE" >/dev/null 2>&1 || LOG_FILE="/tmp/iomatex-postinstall-selftest.log"
touch "$LOG_FILE" >/dev/null 2>&1 || true
exec > >(tee -a "$LOG_FILE") 2>&1
section() {
printf '\n[SECTION] %s\n' "$1"
}
pass() {
TEST_COUNT=$((TEST_COUNT + 1))
PASS_COUNT=$((PASS_COUNT + 1))
printf '[PASS] %s\n' "$1"
}
warn() {
TEST_COUNT=$((TEST_COUNT + 1))
WARN_COUNT=$((WARN_COUNT + 1))
WARN_ITEMS+=("$1")
printf '[WARN] %s\n' "$1"
}
fail() {
TEST_COUNT=$((TEST_COUNT + 1))
FAIL_COUNT=$((FAIL_COUNT + 1))
FAIL_ITEMS+=("$1")
printf '[FAIL] %s\n' "$1"
}
run_quick() {
timeout "${2:-8}" bash -lc "$1" 2>/dev/null
}
have_cmd() {
command -v "$1" >/dev/null 2>&1
}
file_exists() {
[[ -e "$1" ]]
}
unit_exists() {
systemctl list-unit-files "$1" --no-legend 2>/dev/null | grep -q "^$1"
}
unit_active() {
systemctl is-active --quiet "$1"
}
unit_enabled_state() {
systemctl is-enabled "$1" 2>/dev/null || true
}
port_listening() {
ss -ltn 2>/dev/null | awk '{print $4}' | grep -Eq "(^|:)$1$"
}
read_console_port() {
local cfg="/etc/iomatex/console.json"
if [[ -f "$cfg" ]] && have_cmd python3; then
python3 - "$cfg" <<'PY' 2>/dev/null || true
import json, sys
try:
with open(sys.argv[1], "r", encoding="utf-8") as fh:
data = json.load(fh)
print(int(data.get("port", 80)))
except Exception:
pass
PY
return 0
fi
printf '80\n'
}
parse_kv() {
local key="$1"
local text="$2"
awk -F= -v k="$key" '$1 == k { print substr($0, index($0, "=") + 1); exit }' <<<"$text"
}
check_base_system() {
section "Base system"
if have_cmd systemctl; then
pass "systemd detected"
else
fail "systemd is not available"
fi
pass "hostname detected: ${HOSTNAME_SHORT}"
local uptime_text=""
uptime_text="$(uptime -p 2>/dev/null || uptime 2>/dev/null || true)"
[[ -n "$uptime_text" ]] && pass "uptime: ${uptime_text}" || warn "failed to read uptime"
local root_avail=""
root_avail="$(df -h / 2>/dev/null | awk 'NR==2 {print $4}')"
if [[ -n "$root_avail" ]]; then
pass "root filesystem free space: ${root_avail}"
else
warn "failed to read root filesystem free space"
fi
if mountpoint -q /userdata 2>/dev/null || [[ -d /userdata ]]; then
local userdata_avail=""
userdata_avail="$(df -h /userdata 2>/dev/null | awk 'NR==2 {print $4}')"
[[ -n "$userdata_avail" ]] && pass "/userdata free space: ${userdata_avail}" || warn "failed to read /userdata free space"
else
warn "/userdata is not mounted or not present"
fi
local mem_line=""
mem_line="$(free -h 2>/dev/null | awk '/^Mem:/ {print $3 "/" $2 " used"}')"
[[ -n "$mem_line" ]] && pass "memory usage: ${mem_line}" || warn "failed to read memory usage"
local swap_total=""
swap_total="$(free -h 2>/dev/null | awk '/^Swap:/ {print $2}')"
if [[ -z "$swap_total" || "$swap_total" == "0B" || "$swap_total" == "0" ]]; then
warn "swap is disabled"
else
pass "swap configured: ${swap_total}"
fi
local load_text=""
load_text="$(awk '{print $1" "$2" "$3}' /proc/loadavg 2>/dev/null || true)"
[[ -n "$load_text" ]] && pass "load average: ${load_text}" || warn "failed to read load average"
if have_cmd timedatectl; then
local ntp_state=""
ntp_state="$(timedatectl show -p NTPSynchronized --value 2>/dev/null || true)"
local tz_state=""
tz_state="$(timedatectl show -p Timezone --value 2>/dev/null || true)"
if [[ -n "$tz_state" ]]; then
[[ "$ntp_state" == "yes" ]] && pass "timedatectl ok: timezone=${tz_state}, ntp synchronized" || warn "timedatectl reachable: timezone=${tz_state}, ntp not synchronized"
else
warn "timedatectl did not return timezone"
fi
else
warn "timedatectl is not available"
fi
local journal_err_count=""
journal_err_count="$(journalctl -p 3 -xb --no-pager 2>/dev/null | wc -l | tr -d ' ')"
if [[ -n "$journal_err_count" ]]; then
if [[ "$journal_err_count" -eq 0 ]]; then
pass "no priority<=3 entries in current boot journal"
else
warn "journal has ${journal_err_count} priority<=3 entries in current boot"
fi
else
warn "failed to inspect current boot journal"
fi
}
check_network() {
section "Network"
local link_br=""
link_br="$(ip -br link 2>/dev/null || true)"
[[ -n "$link_br" ]] && pass "ip -br link collected" || warn "failed to read ip -br link"
[[ -n "$link_br" ]] && printf '%s\n' "$link_br"
local ip4_text=""
ip4_text="$(ip -4 addr 2>/dev/null || true)"
[[ -n "$ip4_text" ]] && pass "IPv4 addresses collected" || warn "failed to read IPv4 addresses"
if ip link show eth0 >/dev/null 2>&1; then
pass "eth0 interface exists"
local carrier=""
carrier="$(cat /sys/class/net/eth0/carrier 2>/dev/null || true)"
if [[ "$carrier" == "1" ]]; then
pass "eth0 carrier detected"
else
warn "eth0 has no carrier"
fi
else
warn "eth0 interface is absent"
fi
local default_route=""
default_route="$(ip route show default 2>/dev/null | head -n1 || true)"
[[ -n "$default_route" ]] && pass "default route: ${default_route}" || warn "default route is missing"
local nameserver_count=""
nameserver_count="$(awk '/^nameserver / {count++} END {print count+0}' /etc/resolv.conf 2>/dev/null)"
if [[ -n "$nameserver_count" && "$nameserver_count" -gt 0 ]]; then
pass "DNS resolver configured with ${nameserver_count} nameserver(s)"
if run_quick "getent ahostsv4 deb.debian.org >/dev/null" 5; then
pass "DNS lookup works"
else
warn "DNS lookup failed for deb.debian.org"
fi
else
warn "no nameserver entries in /etc/resolv.conf"
fi
if unit_active "NetworkManager.service"; then
pass "NetworkManager.service active"
elif unit_exists "NetworkManager.service"; then
fail "NetworkManager.service installed but inactive"
else
fail "NetworkManager.service not installed"
fi
local dstate=""
dstate="$(ps -eo pid,ppid,stat,comm,args | awk '$3 ~ /^D/ || $4 ~ /^(RTW_XMIT_THREAD|RTW_RECV_THREAD|RTW_CMD_THREAD|RTWHALXT)$/' || true)"
if [[ -n "$dstate" ]]; then
fail "D-state or RTL8723DS worker threads detected"
printf '%s\n' "$dstate"
else
pass "no D-state threads detected"
fi
}
check_wifi_ap() {
section "Wi-Fi / AP failover"
local status_script="/usr/local/sbin/iomatex-wifi-status"
if [[ -x "$status_script" ]]; then
pass "wifi status script exists: ${status_script}"
else
fail "wifi status script missing or not executable: ${status_script}"
return 0
fi
local wifi_status=""
wifi_status="$(run_quick "$status_script" 8 || true)"
if [[ -n "$wifi_status" && "$(parse_kv IFACE "$wifi_status")" != "" ]]; then
pass "wifi status script returned parseable output"
printf '%s\n' "$wifi_status"
else
fail "wifi status script failed or returned unparsable output"
return 0
fi
local eth_carrier=""
local ap_active=""
local driver_loaded=""
eth_carrier="$(parse_kv ETH_CARRIER "$wifi_status")"
ap_active="$(parse_kv AP_ACTIVE "$wifi_status")"
driver_loaded="$(parse_kv DRIVER_LOADED "$wifi_status")"
if [[ "$eth_carrier" == "1" ]]; then
[[ "$ap_active" == "0" ]] && pass "eth0 present -> AP inactive as expected" || fail "eth0 present -> AP unexpectedly active"
[[ "$driver_loaded" == "no" ]] && pass "eth0 present -> RTL8723DS unloaded as expected" || fail "eth0 present -> RTL8723DS unexpectedly loaded"
elif [[ "$eth_carrier" == "0" ]]; then
warn "eth0 has no carrier; showing current AP state without failing automatically"
[[ -n "$ap_active" ]] && printf 'AP_ACTIVE=%s DRIVER_LOADED=%s\n' "$ap_active" "$driver_loaded"
else
warn "eth0 carrier state is unknown in wifi status output"
fi
for unit in iomatex-ap-watch.timer iomatex-wifi-dstate-watchdog.timer iomatex-ap-resetd.service; do
if unit_exists "$unit"; then
if unit_active "$unit"; then
pass "${unit} active"
else
warn "${unit} installed but inactive"
fi
else
warn "${unit} not installed"
fi
done
}
check_mqtt() {
section "MQTT"
if unit_active "mosquitto.service"; then
pass "mosquitto.service active"
elif unit_exists "mosquitto.service"; then
fail "mosquitto.service installed but inactive"
else
warn "mosquitto.service not installed"
return 0
fi
if port_listening 1883; then
pass "port 1883 listening"
else
fail "port 1883 is not listening"
fi
if [[ -f /etc/mosquitto/mosquitto.conf ]]; then
pass "mosquitto config exists"
else
fail "mosquitto config missing"
fi
if have_cmd mosquitto; then
if run_quick "mosquitto -c /etc/mosquitto/mosquitto.conf -p 0 -d >/dev/null" 5; then
pass "mosquitto config accepted by daemon"
else
warn "mosquitto config validation by daemon failed"
fi
else
warn "mosquitto binary not available for config validation"
fi
if have_cmd mosquitto_pub && have_cmd mosquitto_sub; then
local topic="iomatex/selftest/${HOSTNAME_SHORT}/$$"
local payload="ping-$(date +%s)"
local captured=""
captured="$(
timeout 8 bash -lc "
mosquitto_sub -h 127.0.0.1 -p 1883 -t '$topic' -C 1 2>/dev/null &
subpid=\$!
sleep 1
mosquitto_pub -h 127.0.0.1 -p 1883 -t '$topic' -m '$payload' 2>/dev/null || true
wait \$subpid 2>/dev/null || true
" | tail -n1
)"
if [[ "$captured" == "$payload" ]]; then
pass "local MQTT pub/sub smoke test passed"
else
fail "local MQTT pub/sub smoke test failed"
fi
else
warn "mosquitto_pub/sub not available; skipping MQTT smoke test"
fi
}
check_reverse_tunnels() {
section "Reverse tunnels"
local unit=""
for unit in iomatex-rt-cockpit.service iomatex-rt-webui.service iomatex-rt-z2m.service; do
if unit_exists "$unit"; then
if unit_active "$unit"; then
pass "${unit} active"
else
warn "${unit} installed but inactive"
fi
else
warn "${unit} not installed"
fi
done
}
check_console() {
section "Web UI / console"
local console_port=""
console_port="$(read_console_port)"
if unit_exists "iomatex-console.service"; then
if unit_active "iomatex-console.service"; then
pass "iomatex-console.service active"
else
fail "iomatex-console.service installed but inactive"
fi
else
warn "iomatex-console.service not installed"
return 0
fi
if port_listening "$console_port"; then
pass "console port listening on ${console_port}"
else
fail "console port ${console_port} is not listening"
fi
if run_quick "curl -fsS http://127.0.0.1:${console_port}/api/status >/dev/null" 5; then
pass "console /api/status responded on port ${console_port}"
else
fail "console /api/status did not respond on port ${console_port}"
fi
}
check_cockpit() {
section "Cockpit"
if unit_exists "cockpit.socket"; then
unit_active "cockpit.socket" && pass "cockpit.socket active" || warn "cockpit.socket installed but inactive"
else
warn "cockpit.socket not installed"
fi
if unit_exists "cockpit.service"; then
unit_active "cockpit.service" && pass "cockpit.service active" || warn "cockpit.service installed but inactive"
else
warn "cockpit.service not installed"
fi
if port_listening 9090; then
pass "port 9090 listening"
if run_quick "curl -kfsS https://127.0.0.1:9090 >/dev/null" 5; then
pass "cockpit HTTPS endpoint responded"
else
warn "cockpit port is open but HTTPS probe failed"
fi
else
warn "port 9090 not listening"
fi
}
check_z2m() {
section "Zigbee2MQTT"
local z2m_dir="/opt/zigbee2mqtt"
local z2m_cfg="/opt/zigbee2mqtt/data/configuration.yaml"
local z2m_data="/opt/zigbee2mqtt/data"
if unit_exists "zigbee2mqtt.service"; then
if unit_active "zigbee2mqtt.service"; then
pass "zigbee2mqtt.service active"
else
warn "zigbee2mqtt.service installed but inactive"
fi
else
warn "zigbee2mqtt.service not installed"
fi
if unit_exists "iomatex-z2m-web.service"; then
unit_active "iomatex-z2m-web.service" && pass "iomatex-z2m-web.service active" || warn "iomatex-z2m-web.service installed but inactive"
else
warn "iomatex-z2m-web.service not installed"
fi
[[ -d "$z2m_dir" ]] && pass "Zigbee2MQTT dir exists: ${z2m_dir}" || warn "Zigbee2MQTT dir missing: ${z2m_dir}"
[[ -f "$z2m_cfg" ]] && pass "Zigbee2MQTT configuration exists" || warn "Zigbee2MQTT configuration missing"
[[ -d "$z2m_data" ]] && pass "Zigbee2MQTT data dir exists" || warn "Zigbee2MQTT data dir missing"
if port_listening 8081; then
pass "Zigbee2MQTT web port 8081 listening"
else
warn "Zigbee2MQTT web port 8081 is not listening"
fi
if [[ -f "$z2m_cfg" ]]; then
if grep -Eq '^[[:space:]]*serial:[[:space:]]*$|^[[:space:]]*port:[[:space:]]*' "$z2m_cfg"; then
pass "Zigbee2MQTT serial/coordinator config present"
else
warn "Zigbee2MQTT config does not expose an obvious serial/coordinator entry"
fi
fi
if compgen -G "/dev/serial/by-id/*" >/dev/null 2>&1 || compgen -G "/dev/ttyUSB*" >/dev/null 2>&1 || compgen -G "/dev/ttyACM*" >/dev/null 2>&1; then
pass "potential Zigbee coordinator device detected"
else
warn "no Zigbee coordinator device detected"
fi
}
check_itscreen() {
section "It-screen runtime"
local its_bin="/opt/itscreen/bin/itscreen"
local its_run="/usr/local/bin/itscreen-run"
[[ -x "$its_bin" ]] && pass "itscreen binary exists: ${its_bin}" || warn "itscreen binary missing: ${its_bin}"
[[ -x "$its_run" ]] && pass "itscreen launcher exists: ${its_run}" || warn "itscreen launcher missing: ${its_run}"
if unit_exists "itscreen-x11.service"; then
if unit_active "itscreen-x11.service"; then
pass "itscreen-x11.service active"
else
warn "itscreen-x11.service installed but inactive"
fi
else
warn "itscreen-x11.service not installed"
return 0
fi
if pgrep -af '/opt/itscreen/bin/itscreen|^itscreen$' >/dev/null 2>&1; then
pass "itscreen process detected"
else
warn "itscreen process not detected"
fi
[[ -d /run/itscreen ]] && pass "itscreen runtime dir exists: /run/itscreen" || warn "itscreen runtime dir missing: /run/itscreen"
}
check_critical_files() {
section "Critical files / directories"
local path=""
for path in \
/opt/itscreen \
/opt/zigbee2mqtt \
/opt/iomatex-console \
/usr/local/sbin/iomatex-wifi-status \
/usr/local/sbin/iomatex-ap-watch; do
[[ -e "$path" ]] && pass "present: ${path}" || warn "missing: ${path}"
done
if [[ -f /etc/iomatex/ap.env ]]; then
pass "present: /etc/iomatex/ap.env"
else
warn "missing: /etc/iomatex/ap.env"
fi
if [[ -f /userdata/device-id ]]; then
local device_id=""
device_id="$(tr -d ' \n\r' </userdata/device-id 2>/dev/null || true)"
[[ -n "$device_id" ]] && pass "present: /userdata/device-id (${device_id})" || warn "/userdata/device-id exists but is empty"
else
warn "missing: /userdata/device-id"
fi
}
check_logs() {
section "Logs / recent failures"
local failed_units=""
failed_units="$(systemctl --failed --no-legend --plain 2>/dev/null | awk '{print $1}' || true)"
if [[ -z "$failed_units" ]]; then
pass "no failed systemd units"
else
warn "failed systemd units detected"
printf '%s\n' "$failed_units"
fi
local unit=""
for unit in iomatex-console.service mosquitto.service zigbee2mqtt.service iomatex-ap-watch.service iomatex-wifi-dstate-watchdog.service itscreen-x11.service; do
if unit_exists "$unit"; then
local err_count=""
err_count="$(journalctl -u "$unit" -p err --since '24 hours ago' --no-pager 2>/dev/null | wc -l | tr -d ' ')"
if [[ -n "$err_count" && "$err_count" -gt 0 ]]; then
warn "${unit} has ${err_count} error-priority log lines in the last 24h"
else
pass "${unit} has no error-priority log lines in the last 24h"
fi
fi
done
}
summary() {
local overall="PASS"
[[ "$FAIL_COUNT" -gt 0 ]] && overall="FAIL"
[[ "$FAIL_COUNT" -eq 0 && "$WARN_COUNT" -gt 0 ]] && overall="WARN"
printf '\n==================================================\n'
printf 'SUMMARY\n'
printf 'PASS: %s\n' "$PASS_COUNT"
printf 'WARN: %s\n' "$WARN_COUNT"
printf 'FAIL: %s\n' "$FAIL_COUNT"
printf 'OVERALL: %s\n' "$overall"
if [[ "${#FAIL_ITEMS[@]}" -gt 0 ]]; then
printf 'Failing checks:\n'
printf ' - %s\n' "${FAIL_ITEMS[@]}"
fi
if [[ "${#WARN_ITEMS[@]}" -gt 0 ]]; then
printf 'Warnings:\n'
printf ' - %s\n' "${WARN_ITEMS[@]}"
fi
printf 'Details log: %s\n' "$LOG_FILE"
printf '==================================================\n'
[[ "$FAIL_COUNT" -eq 0 ]]
}
main() {
printf '==================================================\n'
printf 'IOMATEX EDGE POST-INSTALL SELFTEST\n'
printf 'Started: %s\n' "$START_TS"
printf 'Host: %s\n' "$HOSTNAME_SHORT"
printf 'Log: %s\n' "$LOG_FILE"
printf '==================================================\n'
check_base_system
check_network
check_wifi_ap
check_mqtt
check_reverse_tunnels
check_console
check_cockpit
check_z2m
check_itscreen
check_critical_files
check_logs
summary
}
main
exit $?

View File

@ -2,14 +2,14 @@
set -euo pipefail
# ======================================
# IOMATEX FAILOVER AP + WiFi Setup UI
# IOMATEX FAILOVER AP ONLY
# Debian 11 / NetworkManager
# Single Wi-Fi card: wlan0
#
# Working policy:
# - eth0 carrier present => AP OFF and Wi-Fi kept quiet
# - eth0 carrier present => AP OFF and Wi-Fi hard-off/runtime-off
# - eth0 carrier absent => Wi-Fi is raised and wlan0 runs AP mode
# - UI "Connect" => AP down -> try STA connect -> if fail -> AP back
# - STA onboarding is disabled on this hardware revision
#
# Defaults:
# - AP SSID = Iomatex <hostname>
@ -41,9 +41,10 @@ AP_CHANNEL="6"
APT_UPDATED=0
LAST_WRITE_CHANGED=0
SYSTEMD_UNITS_CHANGED=0
UI_SERVICE_CHANGED=0
WIFI_BASELINE_CHANGED=0
WATCH_SERVICE_CHANGED=0
RESETD_SERVICE_CHANGED=0
DSTATE_SERVICE_CHANGED=0
EXISTING_PASSWORD_MODE=""
EXISTING_CUSTOM_PASSWORD=""
@ -328,11 +329,11 @@ ensure_nm_wifi_profile() {
need_root
check_text_safety
log "=== IOMATEX FAILOVER AP + WiFi Setup START ==="
log "=== IOMATEX FAILOVER AP ONLY START ==="
log "LOG: $LOG"
step "Install packages"
apt_install_missing hostapd dnsmasq iw rfkill python3 network-manager iptables
apt_install_missing hostapd dnsmasq iw rfkill wireless-regdb python3 network-manager iptables
step "Prefer iptables-legacy if available"
if update-alternatives --list iptables >/dev/null 2>&1; then
@ -346,8 +347,185 @@ step "Disable stock hostapd and dnsmasq"
systemctl_disable_now_safe hostapd
systemctl_disable_now_safe dnsmasq
step "Apply Wi-Fi baseline"
mkdir -p /etc/iomatex /etc/hostapd /etc/dnsmasq.d /opt/iomatex-wifi-ui /usr/local/sbin /etc/modprobe.d /etc/NetworkManager/conf.d
if command -v iw >/dev/null 2>&1; then
iw reg set AE || true
fi
write_managed_file /etc/modprobe.d/cfg80211.conf 0644 <<'EOF'
options cfg80211 ieee80211_regdom=AE
EOF
if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then
WIFI_BASELINE_CHANGED=1
fi
write_managed_file /etc/NetworkManager/conf.d/10-iomatex-disable-p2p.conf 0644 <<'EOF'
[main]
plugins=keyfile
[keyfile]
unmanaged-devices=interface-name:p2p0;interface-name:p2p-dev-p2p0;interface-name:p2p-dev-wlan0
[device]
wifi.scan-rand-mac-address=no
[connection]
wifi.powersave=2
EOF
if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then
WIFI_BASELINE_CHANGED=1
fi
WPA_CFG_CHANGED=0
WPA_CFGS=()
[[ -f /etc/wpa_supplicant.conf ]] && WPA_CFGS+=(/etc/wpa_supplicant.conf)
[[ -f /etc/wpa_supplicant/wpa_supplicant.conf ]] && WPA_CFGS+=(/etc/wpa_supplicant/wpa_supplicant.conf)
if [[ "${#WPA_CFGS[@]}" -eq 0 ]]; then
WPA_CFGS+=(/etc/wpa_supplicant.conf)
fi
for WPA_CFG in "${WPA_CFGS[@]}"; do
tmp_wpa="$(mktemp)"
if [[ -f "$WPA_CFG" ]]; then
awk '
BEGIN { done=0 }
/^[[:space:]]*p2p_disabled[[:space:]]*=/ {
if (!done) {
print "p2p_disabled=1"
done=1
}
next
}
{ print }
END {
if (!done) {
print "p2p_disabled=1"
}
}
' "$WPA_CFG" >"$tmp_wpa"
else
printf 'p2p_disabled=1\n' >"$tmp_wpa"
fi
if [[ -f "$WPA_CFG" ]] && cmp -s "$tmp_wpa" "$WPA_CFG"; then
rm -f "$tmp_wpa"
else
install -D -o root -g root -m 0644 "$tmp_wpa" "$WPA_CFG"
rm -f "$tmp_wpa"
WPA_CFG_CHANGED=1
fi
done
if [[ "$WPA_CFG_CHANGED" -eq 1 ]]; then
WIFI_BASELINE_CHANGED=1
fi
systemctl_disable_now_safe wpa_supplicant
write_managed_file /usr/local/sbin/iomatex-wifi-runtime-off 0755 <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
WIFI_IFACE="${1:-wlan0}"
P2P_IFACE="${2:-p2p0}"
DRIVER_UNAVAILABLE_STATE="/run/iomatex-wifi-driver-unavailable.state"
for unit in \
iomatex-wifi-ui.service \
iomatex-hostapd.service \
iomatex-dnsmasq.service \
wpa_supplicant.service
do
systemctl stop "$unit" >/dev/null 2>&1 || true
done
if command -v nmcli >/dev/null 2>&1; then
nmcli device disconnect "$WIFI_IFACE" >/dev/null 2>&1 || true
nmcli radio wifi off >/dev/null 2>&1 || true
nmcli dev set "$WIFI_IFACE" managed no >/dev/null 2>&1 || true
fi
rfkill block wifi >/dev/null 2>&1 || true
ip addr flush dev "$WIFI_IFACE" >/dev/null 2>&1 || true
ip link set "$WIFI_IFACE" down >/dev/null 2>&1 || true
ip link set "$P2P_IFACE" down >/dev/null 2>&1 || true
modprobe -r RTL8723DS >/dev/null 2>&1 || rmmod RTL8723DS >/dev/null 2>&1 || true
rm -f "$DRIVER_UNAVAILABLE_STATE" >/dev/null 2>&1 || true
echo "--- iomatex-wifi-runtime-off diagnostics ---"
lsmod | grep -i RTL8723DS || true
ps -eo pid,ppid,stat,comm,args | grep -E 'RTW_|RTL8723DS' | grep -v grep || true
EOF
if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then
WIFI_BASELINE_CHANGED=1
fi
write_managed_file /usr/local/sbin/iomatex-wifi-runtime-on 0755 <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
WIFI_IFACE="${1:-wlan0}"
DRIVER_MODULE_NAME="RTL8723DS"
DRIVER_MODULE_PATH="/usr/lib/modules/RTL8723DS.ko"
DRIVER_UNAVAILABLE_STATE="/run/iomatex-wifi-driver-unavailable.state"
iface_present() {
ip link show dev "$WIFI_IFACE" >/dev/null 2>&1
}
driver_loaded() {
lsmod | grep -iq "^${DRIVER_MODULE_NAME}\b"
}
if ! iface_present && ! driver_loaded; then
if [[ ! -f "$DRIVER_MODULE_PATH" ]]; then
touch "$DRIVER_UNAVAILABLE_STATE"
logger -t iomatex-wifi-runtime-on "Wi-Fi driver load failed: missing module path $DRIVER_MODULE_PATH"
exit 0
fi
if ! insmod "$DRIVER_MODULE_PATH" >/dev/null 2>&1; then
touch "$DRIVER_UNAVAILABLE_STATE"
logger -t iomatex-wifi-runtime-on "Wi-Fi driver load failed: insmod $DRIVER_MODULE_PATH returned non-zero"
exit 0
fi
sleep 3
if ! iface_present; then
touch "$DRIVER_UNAVAILABLE_STATE"
logger -t iomatex-wifi-runtime-on "Wi-Fi driver load failed: $WIFI_IFACE did not appear after insmod"
exit 0
fi
fi
rm -f "$DRIVER_UNAVAILABLE_STATE" >/dev/null 2>&1 || true
rfkill unblock wifi >/dev/null 2>&1 || true
if command -v nmcli >/dev/null 2>&1; then
nmcli radio wifi on >/dev/null 2>&1 || true
fi
iface_present || exit 0
ip link set "$WIFI_IFACE" down >/dev/null 2>&1 || true
sleep 1
ip link set "$WIFI_IFACE" up >/dev/null 2>&1 || true
EOF
if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then
WIFI_BASELINE_CHANGED=1
fi
write_managed_file /usr/local/sbin/iomatex-wifi-quiet 0755 <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
exec /usr/local/sbin/iomatex-wifi-runtime-off "$@"
EOF
if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then
WIFI_BASELINE_CHANGED=1
fi
if [[ "$WIFI_BASELINE_CHANGED" -eq 1 ]]; then
systemctl_restart_safe NetworkManager
fi
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 <<EOF
IFACE="$IFACE"
@ -438,7 +616,6 @@ 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
@ -469,54 +646,22 @@ def run(cmd):
HTML = """<!doctype html><html><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>IOMATEX Wi-Fi Setup</title>
<title>IOMATEX AP Setup</title>
<style>
body{font-family:system-ui,Segoe UI,Roboto,Arial;margin:24px;max-width:760px}
.card{border:1px solid #ddd;border-radius:12px;padding:16px;margin:12px 0}
label{display:block;margin:8px 0 4px}
input{width:100%;padding:10px;border:1px solid #ccc;border-radius:10px}
button{padding:10px 14px;border-radius:10px;border:1px solid #111;background:#111;color:#fff;cursor:pointer}
.small{color:#666;font-size:13px}
.inlineRow{display:flex;gap:10px;align-items:center}
.inlineRow input{flex:1 1 auto}
.toggleBtn{white-space:nowrap}
pre{white-space:pre-wrap;background:#f6f6f6;border-radius:10px;padding:12px}
</style></head><body>
<h2>IOMATEX Wi-Fi Setup</h2>
<h2>IOMATEX Local AP Setup</h2>
<div class="card">
<b>Connect to external Wi-Fi</b>
<div class="small">In AP mode scanning may be unavailable; enter SSID manually.</div>
<label>SSID</label><input id="ssid" placeholder="e.g. HotelWiFi">
<label>Password</label>
<div class="inlineRow">
<input id="pass" type="password" placeholder="(empty = open network)">
<button type="button" class="toggleBtn" onclick="togglePassword(this)">Show</button>
</div>
<div class="small">After successful connection, the access point __HOSTNAME_NOTE__ will disappear.</div>
<div style="margin-top:12px"><button onclick="connect()">Connect</button></div>
<div class="small" id="msg" style="margin-top:10px"></div>
<b>AP-only policy</b>
<div class="small">This access point provides local setup and rescue access to the device.</div>
<div class="small">STA onboarding is disabled on this hardware revision due to Wi-Fi driver stability policy.</div>
<div class="small" style="margin-top:10px">Active AP: __HOSTNAME_NOTE__</div>
</div>
<script>
function togglePassword(btn){
const pass=document.getElementById("pass");
const showing = pass.type === "text";
pass.type = showing ? "password" : "text";
if(btn){ btn.textContent = showing ? "Show" : "Hide"; }
}
async function connect(){
const ssid=document.getElementById("ssid").value.trim();
const pass=document.getElementById("pass").value;
const msg=document.getElementById("msg");
if(!ssid){ msg.textContent="SSID required"; return; }
msg.textContent="Connecting... (AP may drop if STA connects)";
const r = await fetch("/api/connect",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},
body:new URLSearchParams({ssid,pass}).toString()});
const j = await r.json();
msg.textContent = (j.ok ? "OK: " : "ERROR: ") + (j.output || "");
}
</script>
</body></html>
"""
HTML = HTML.replace("__HOSTNAME_NOTE__", HOSTNAME if HOSTNAME else "device access point")
@ -546,16 +691,16 @@ class Handler(BaseHTTPRequestHandler):
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")
self._send(
410,
json.dumps(
{
"ok": False,
"output": "STA mode disabled on this device; AP-only policy is enforced",
}
),
"application/json",
)
return
self._send(404, "Not Found", "text/plain; charset=utf-8")
@ -568,9 +713,6 @@ def main():
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]
@ -588,9 +730,6 @@ RestartSec=2
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-sync-config 0755 <<'EOF'
@ -765,17 +904,31 @@ write_managed_file /usr/local/sbin/iomatex-ap-up 0755 <<'EOF'
set -euo pipefail
. /etc/iomatex/ap.env
DRIVER_UNAVAILABLE_STATE="/run/iomatex-wifi-driver-unavailable.state"
iface_present() {
ip link show dev "$IFACE" >/dev/null 2>&1
}
/usr/local/sbin/iomatex-ap-sync-config >/dev/null 2>&1 || true
. /etc/iomatex/ap.env
/usr/local/sbin/iomatex-wifi-runtime-on "$IFACE" >/dev/null 2>&1 || true
if ! iface_present; then
touch "$DRIVER_UNAVAILABLE_STATE"
logger -t iomatex-ap-up "AP bring-up skipped: Wi-Fi interface $IFACE is absent and RTL8723DS auto-load is disabled"
exit 0
fi
rm -f "$DRIVER_UNAVAILABLE_STATE" >/dev/null 2>&1 || true
rfkill unblock wifi >/dev/null 2>&1 || true
if command -v nmcli >/dev/null 2>&1; then
nmcli dev disconnect "$IFACE" >/dev/null 2>&1 || true
nmcli radio wifi on >/dev/null 2>&1 || true
nmcli dev set "$IFACE" managed no >/dev/null 2>&1 || true
fi
systemctl stop wpa_supplicant.service >/dev/null 2>&1 || true
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"
@ -794,6 +947,7 @@ set -euo pipefail
systemctl stop iomatex-hostapd.service 2>/dev/null || true
systemctl stop iomatex-dnsmasq.service 2>/dev/null || true
systemctl stop iomatex-wifi-ui.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
rm -f /run/iomatex-ap-landing.state 2>/dev/null || true
@ -801,12 +955,10 @@ rm -f /run/iomatex-ap-landing.state 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
nmcli radio wifi off >/dev/null 2>&1 || true
nmcli dev set "$IFACE" managed no >/dev/null 2>&1 || true
fi
ip link set "$IFACE" down >/dev/null 2>&1 || true
rfkill block wifi >/dev/null 2>&1 || true
/usr/local/sbin/iomatex-wifi-runtime-off "$IFACE" p2p0 >/dev/null 2>&1 || true
EOF
write_managed_file /usr/local/sbin/iomatex-wifi-status 0755 <<'EOF'
@ -816,29 +968,40 @@ set -euo pipefail
ap_active=0
systemctl is-active --quiet iomatex-hostapd.service && ap_active=1
eth_carrier="$(cat /sys/class/net/eth0/carrier 2>/dev/null || echo 0)"
wifi_radio="n/a"
rfkill_state="unknown"
driver_loaded=no
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)"
wifi_radio="$(nmcli radio wifi 2>/dev/null || 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
rfkill_state="$(rfkill list wifi 2>/dev/null | awk -F': ' '/Soft blocked:/{print $2; exit}' || true)"
lsmod | grep -iq '^RTL8723DS' && driver_loaded=yes
ip4="$(ip -4 -o addr show dev "$IFACE" 2>/dev/null | awk '{print $4}' | head -n1 || true)"
wifi_iface_present=no
p2p_iface_present=no
ip link show dev "$IFACE" >/dev/null 2>&1 && wifi_iface_present=yes
ip link show dev p2p0 >/dev/null 2>&1 && p2p_iface_present=yes
echo "IFACE=$IFACE"
echo "AP_ACTIVE=$ap_active"
echo "ETH_CARRIER=$eth_carrier"
echo "NM_STATE=$nm_state"
echo "NM_CONNECTION=$nm_con"
echo "STA_CONNECTED=$sta_connected"
echo "WIFI_RADIO=$wifi_radio"
echo "RFKILL_SOFT_BLOCKED=$rfkill_state"
echo "DRIVER_LOADED=$driver_loaded"
echo "WIFI_IFACE_PRESENT=$wifi_iface_present"
echo "P2P_IFACE_PRESENT=$p2p_iface_present"
echo "DRIVER_UNAVAILABLE=$(test -f /run/iomatex-wifi-driver-unavailable.state && echo yes || echo no)"
echo "IP4=$ip4"
echo "WATCH_STATE=$(cat /run/iomatex-ap.state 2>/dev/null || echo n/a)"
echo "LANDING_TARGET=$(cat /run/iomatex-ap-landing.state 2>/dev/null || echo unknown)"
echo "DRIVER_DEGRADED=$(test -f /run/iomatex-wifi-driver-degraded.state && echo yes || echo no)"
EOF
write_managed_file /usr/local/sbin/iomatex-ap-refresh-landing 0755 <<'EOF'
@ -905,99 +1068,7 @@ 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; }
AP_LOCK="/run/iomatex-ap.lock"
exec 8>"$AP_LOCK"
flock 8
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
}
wait_for_nm_device_ready() {
local attempt state=""
for attempt in $(seq 1 20); do
state="$(nmcli -t -f DEVICE,STATE dev | awk -F: -v d="$IFACE" '$1==d{print $2; exit}' || true)"
case "$state" in
disconnected|connecting|connected)
return 0
;;
esac
sleep 1
done
echo "ERROR: NetworkManager did not reclaim $IFACE (state=${state:-unknown})" >&2
return 1
}
/usr/local/sbin/iomatex-ap-down >/dev/null 2>&1 || true
rfkill unblock wifi >/dev/null 2>&1 || true
if command -v nmcli >/dev/null 2>&1; then
nmcli radio wifi on >/dev/null 2>&1 || true
fi
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
wait_for_nm_device_ready
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
up_output=""
if ! up_output="$(nmcli --wait 25 con up id "$CN" 2>&1)"; then
echo "ERROR: failed to start Wi-Fi profile '$CN': ${up_output}" >&2
else
echo "INFO: Wi-Fi profile '$CN' activation requested: ${up_output}" >&2
fi
sleep 10
if sta_ok; then
ip4="$(ip -4 -o addr show dev "$IFACE" 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
/usr/local/sbin/iomatex-ap-up >/dev/null 2>&1 || true
echo "ERROR: STA not connected / no IPv4; AP restored (NM_STATE=$(nmcli -t -f DEVICE,STATE dev | awk -F: -v d=\"$IFACE\" '\$1==d{print \$2; exit}' || echo unknown))" >&2
echo "STA mode disabled on this device; AP-only policy is enforced" >&2
exit 10
EOF
@ -1009,6 +1080,7 @@ set -euo pipefail
STATE="/run/iomatex-ap.state"
LOCK="/run/iomatex-ap.lock"
DRIVER_UNAVAILABLE_STATE="/run/iomatex-wifi-driver-unavailable.state"
exec 9>"$LOCK"
flock -n 9 || exit 0
@ -1019,13 +1091,55 @@ eth_ok() {
ap_is_up() { systemctl is-active --quiet iomatex-hostapd.service; }
iface_present() {
ip link show dev "$IFACE" >/dev/null 2>&1
}
driver_loaded() {
lsmod | grep -iq '^RTL8723DS'
}
wifi_radio_enabled() {
command -v nmcli >/dev/null 2>&1 || return 1
[ "$(nmcli radio wifi 2>/dev/null || true)" = "enabled" ]
}
wifi_runtime_needs_off() {
iface_present && return 0
driver_loaded && return 0
wifi_radio_enabled && return 0
return 1
}
if eth_ok; then
ap_is_up && /usr/local/sbin/iomatex-ap-down || true
rm -f "$DRIVER_UNAVAILABLE_STATE" >/dev/null 2>&1 || true
if ap_is_up; then
/usr/local/sbin/iomatex-ap-down || true
elif wifi_runtime_needs_off; then
/usr/local/sbin/iomatex-wifi-runtime-off "$IFACE" p2p0 >/dev/null 2>&1 || true
fi
echo "eth_uplink_ok" > "$STATE"
exit 0
fi
ap_is_up || /usr/local/sbin/iomatex-ap-up
if ap_is_up; then
rm -f "$DRIVER_UNAVAILABLE_STATE" >/dev/null 2>&1 || true
else
if ! iface_present && ! driver_loaded; then
if [[ -f "$DRIVER_UNAVAILABLE_STATE" ]]; then
echo "ap_unavailable_driver_failed" > "$STATE"
exit 0
fi
/usr/local/sbin/iomatex-wifi-runtime-on "$IFACE" >/dev/null 2>&1 || true
if ! iface_present; then
touch "$DRIVER_UNAVAILABLE_STATE"
logger -t iomatex-ap-watch "AP auto-load failed: $IFACE is still absent after runtime-on"
echo "ap_unavailable_driver_failed" > "$STATE"
exit 0
fi
fi
/usr/local/sbin/iomatex-ap-up || true
fi
/usr/local/sbin/iomatex-ap-refresh-landing >/dev/null 2>&1 || true
echo "ap_on_no_eth" > "$STATE"
EOF
@ -1033,6 +1147,87 @@ if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then
WATCH_SERVICE_CHANGED=1
fi
write_managed_file /usr/local/sbin/iomatex-wifi-dstate-watchdog 0755 <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
STATE_FILE="/run/iomatex-wifi-driver-degraded.state"
find_bad_threads() {
ps -eo pid,ppid,stat,comm,args | awk '$3 ~ /^D/ && $4 ~ /^(RTW_XMIT_THREAD|RTW_RECV_THREAD|RTW_CMD_THREAD|RTWHALXT)$/'
}
ap_active() {
systemctl is-active --quiet iomatex-hostapd.service
}
driver_loaded() {
lsmod | grep -iq '^RTL8723DS'
}
bad_threads="$(find_bad_threads || true)"
if [[ -z "$bad_threads" ]]; then
rm -f "$STATE_FILE" 2>/dev/null || true
exit 0
fi
logger -t iomatex-wifi-dstate-watchdog "warning: detected RTL8723DS D-state threads"
printf '%s\n' "$bad_threads" | logger -t iomatex-wifi-dstate-watchdog
if ap_active; then
touch "$STATE_FILE"
logger -t iomatex-wifi-dstate-watchdog "critical: AP active; leaving Wi-Fi up and marking driver degraded"
exit 0
fi
/usr/local/sbin/iomatex-wifi-runtime-off wlan0 p2p0 >/dev/null 2>&1 || true
bad_threads_after="$(find_bad_threads || true)"
if [[ -z "$bad_threads_after" ]] && ! driver_loaded; then
rm -f "$STATE_FILE" 2>/dev/null || true
logger -t iomatex-wifi-dstate-watchdog "warning: runtime-off cleared RTL8723DS degraded state"
exit 0
fi
touch "$STATE_FILE"
logger -t iomatex-wifi-dstate-watchdog "critical: RTL8723DS degraded state persists after runtime-off"
printf '%s\n' "$bad_threads_after" | logger -t iomatex-wifi-dstate-watchdog
exit 0
EOF
write_managed_file /etc/systemd/system/iomatex-wifi-dstate-watchdog.service 0644 <<'EOF'
[Unit]
Description=IOMATEX Wi-Fi D-state watchdog
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/iomatex-wifi-dstate-watchdog
EOF
mark_unit_change_if_needed
if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then
DSTATE_SERVICE_CHANGED=1
fi
write_managed_file /etc/systemd/system/iomatex-wifi-dstate-watchdog.timer 0644 <<'EOF'
[Unit]
Description=IOMATEX Wi-Fi D-state watchdog timer
[Timer]
OnBootSec=10min
OnUnitActiveSec=1h
AccuracySec=1min
Unit=iomatex-wifi-dstate-watchdog.service
[Install]
WantedBy=timers.target
EOF
mark_unit_change_if_needed
if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then
DSTATE_SERVICE_CHANGED=1
fi
write_managed_file /usr/local/sbin/iomatex-ap-resetd 0755 <<'EOF'
#!/usr/bin/env python3
import os
@ -1242,19 +1437,12 @@ fi
/usr/local/sbin/iomatex-ap-sync-config
/usr/local/sbin/iomatex-ap-refresh-landing >/dev/null 2>&1 || true
systemctl enable iomatex-wifi-ui.service >/dev/null 2>&1 || true
systemctl disable iomatex-wifi-ui.service >/dev/null 2>&1 || true
systemctl enable iomatex-ap-watch.timer >/dev/null 2>&1 || true
systemctl enable iomatex-ap-resetd.service >/dev/null 2>&1 || true
systemctl enable iomatex-wifi-dstate-watchdog.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
systemctl stop iomatex-wifi-ui.service >/dev/null 2>&1 || true
if [[ "$WATCH_SERVICE_CHANGED" -eq 1 ]]; then
if systemctl is-active --quiet iomatex-ap-watch.timer; then
@ -1276,6 +1464,16 @@ else
systemctl_start_safe iomatex-ap-resetd.service
fi
if [[ "$DSTATE_SERVICE_CHANGED" -eq 1 ]]; then
if systemctl is-active --quiet iomatex-wifi-dstate-watchdog.timer; then
systemctl_restart_safe iomatex-wifi-dstate-watchdog.timer
else
systemctl_start_safe iomatex-wifi-dstate-watchdog.timer
fi
else
systemctl_start_safe iomatex-wifi-dstate-watchdog.timer
fi
step "Initial enforce"
/usr/local/sbin/iomatex-ap-watch || true
@ -1290,7 +1488,7 @@ echo "AP MODE : ${PASSWORD_MODE}"
echo "FACTORY AP PASS : ${FACTORY_AP_PASSWORD}"
echo "AP IP : ${AP_IP}"
echo "PRIMARY UI : http://${AP_IP}/ (console when healthy)"
echo "FALLBACK UI: http://${AP_IP}:${UI_PORT}/ (legacy Wi-Fi rescue UI)"
echo "FALLBACK UI: http://${AP_IP}:${UI_PORT}/ (local AP-only rescue UI)"
echo
echo "TEST:"
echo " - No eth0 link: connect to WiFi SSID=${SSID}"
@ -1300,5 +1498,5 @@ echo
echo "DIAG:"
echo " /usr/local/sbin/iomatex-wifi-status"
echo " /usr/local/sbin/iomatex-ap-reset-password"
echo " systemctl status iomatex-wifi-ui.service iomatex-ap-watch.timer iomatex-ap-resetd.service --no-pager"
echo " journalctl -u iomatex-wifi-ui.service -u iomatex-ap-watch.service -u iomatex-ap-resetd.service --no-pager -n 200"
echo " systemctl status iomatex-wifi-ui.service iomatex-ap-watch.timer iomatex-ap-resetd.service iomatex-wifi-dstate-watchdog.timer --no-pager"
echo " journalctl -u iomatex-wifi-ui.service -u iomatex-ap-watch.service -u iomatex-ap-resetd.service -u iomatex-wifi-dstate-watchdog.service --no-pager -n 200"