#!/usr/bin/env bash set -Eeuo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_PATH="${SCRIPT_DIR}/$(basename "${BASH_SOURCE[0]}")" 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 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" 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=() FAILED_STAGES=() STAGE_ORDER=( "stage_env" "stage_wifi" "stage_mqtt" "stage_z2m" "stage_ui" "stage_itscreen" "stage_reverse_tunnels" ) 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')" "$*" } log_err() { printf '[%s] %s\n' "$(date -u +'%F %T UTC')" "$*" >&2 } 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 /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: - 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 } 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" 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" </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" </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 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" ;; stage_itscreen) printf '%s\n' "stage_itscreen_install.sh" ;; esac } find_stage_installer() { local stage="$1" local stage_dir="${PROJECT_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="${PROJECT_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 " - 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 " - 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 --reset-state) RESET_STATE=1 shift ;; --from) [[ $# -ge 2 ]] || die "--from requires a stage name" 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 ;; *) if [[ -z "$SOURCE_PATH" ]]; then SOURCE_PATH="$1" shift else die "Unknown argument: $1" fi ;; 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 "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 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 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:-}" sync sleep 2 systemctl reboot exit 0 fi done record_summary_from_state print_summary 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