Iomatex_OS/local_installer.sh

1585 lines
42 KiB
Bash
Executable File

#!/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}"
ORIG_STDIN_IS_TTY=0
ORIG_STDOUT_IS_TTY=0
[[ -t 0 ]] && ORIG_STDIN_IS_TTY=1
[[ -t 1 ]] && ORIG_STDOUT_IS_TTY=1
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}"
IOMATEX_GIT_URL="${IOMATEX_GIT_URL:-https://git.it-screen.com/An-J/Iomatex_OS.git}"
IOMATEX_GIT_BRANCH="${IOMATEX_GIT_BRANCH:-master}"
IOMATEX_GIT_DIR="${IOMATEX_GIT_DIR:-/opt/iomatex/Iomatex_OS}"
IOMATEX_GIT_TOKEN="${IOMATEX_GIT_TOKEN:-}"
RESUME_POST_REBOOT=0
OPEN_POST_REBOOT_WINDOW=0
RESET_STATE=0
NON_INTERACTIVE=0
WITH_OPTIONAL_ALL=0
USE_GIT_SOURCE=0
SOURCE_PATH=""
FROM_STAGE=""
ONLY_STAGES_RAW=""
GIT_URL="$IOMATEX_GIT_URL"
GIT_BRANCH="$IOMATEX_GIT_BRANCH"
GIT_AUTH_MODE="none"
GIT_EFFECTIVE_URL=""
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"
SOURCE_TYPE=""
SOURCE_DESCRIPTION=""
SOURCE_REPO_URL=""
SOURCE_BRANCH=""
SOURCE_COMMIT=""
INTERACTIVE_MODE="interactive"
REBOOT_CONTINUATION_USED=0
SUCCESS_STAGES=()
SKIPPED_STAGES=()
SKIPPED_BY_SELECTION_STAGES=()
SKIPPED_MISSING_STAGES=()
FAILED_STAGES=()
SELECTED_STAGES=()
STAGE_ORDER=(
"stage_env"
"stage_wifi"
"stage_mqtt"
"stage_z2m"
"stage_ui"
"stage_itscreen"
"stage_reverse_tunnels"
)
MUST_HAVE_STAGES=(
"stage_env"
"stage_mqtt"
"stage_ui"
"stage_itscreen"
)
OPTIONAL_STAGES=(
"stage_wifi"
"stage_z2m"
"stage_reverse_tunnels"
)
is_known_stage() {
local wanted="$1"
local stage
for stage in "${STAGE_ORDER[@]}"; do
[[ "$stage" == "$wanted" ]] && return 0
done
return 1
}
in_array() {
local wanted="$1"
shift || true
local item
for item in "$@"; do
[[ "$item" == "$wanted" ]] && return 0
done
return 1
}
join_by_comma() {
local IFS=","
echo "$*"
}
join_by_space() {
local IFS=" "
echo "$*"
}
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 --git
sudo bash ./local_installer.sh --git-url <url>
sudo bash ./local_installer.sh --branch <branch>
sudo bash ./local_installer.sh --non-interactive
sudo bash ./local_installer.sh --with-optional-all
sudo bash ./local_installer.sh --only stage_env,stage_mqtt,stage_ui
sudo bash ./local_installer.sh --from stage_mqtt
sudo bash ./local_installer.sh --reset-state
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 --resume-post-reboot
bash ./local_installer.sh --open-post-reboot-window
Behavior:
- runs stage installers in fixed order
- by default syncs stages from git and installs from the checkout
- explicit source path may be a Prod directory or an archive containing Prod/
- if stage_env is selected and succeeds, reboot is mandatory before continuing
- after reboot continuation resumes via systemd and shows live progress in lxterminal on DISPLAY=:0
- lxterminal is also started from desktop autologin as a fallback
- skips missing stage directories and missing installers
- stores project root, source metadata, selected stages, and stage statuses in local_installer.state
- stops on first stage failure
Git defaults:
- IOMATEX_GIT_URL=https://git.it-screen.com/An-J/Iomatex_OS.git
- IOMATEX_GIT_BRANCH=master
- IOMATEX_GIT_DIR=/opt/iomatex/Iomatex_OS
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"
}
apt_source_list_files() {
local path
[[ -f /etc/apt/sources.list ]] && printf '%s\n' /etc/apt/sources.list
shopt -s nullglob
for path in /etc/apt/sources.list.d/*.list; do
[[ -f "$path" ]] && printf '%s\n' "$path"
done
shopt -u nullglob
}
apt_source_deb822_files() {
local path
shopt -s nullglob
for path in /etc/apt/sources.list.d/*.sources; do
[[ -f "$path" ]] && printf '%s\n' "$path"
done
shopt -u nullglob
}
backup_apt_source_files() {
local path=""
local backup_path=""
while IFS= read -r path; do
[[ -n "$path" ]] || continue
backup_path="${path}.bak.iomatex"
[[ -f "$backup_path" ]] || cp -a "$path" "$backup_path"
done < <(
apt_source_list_files
apt_source_deb822_files
)
}
disable_apt_translations() {
cat >/etc/apt/apt.conf.d/99no-translations <<'EOF'
Acquire::Languages "none";
EOF
chmod 0644 /etc/apt/apt.conf.d/99no-translations
log "APT translations disabled"
}
sanitize_apt_list_files() {
local path=""
while IFS= read -r path; do
[[ -n "$path" ]] || continue
sed -i -E 's/^[[:space:]]*deb-src /# deb-src /g' "$path"
sed -i -E 's|^[[:space:]]*deb .*bullseye-backports.*|# &|g' "$path"
sed -i -E '/^[[:space:]]*(deb|# deb|deb-src|# deb-src)[[:space:]].*bullseye/ s|https?://mirrors\.ustc\.edu\.cn/debian-security|http://deb.debian.org/debian-security|g' "$path"
sed -i -E '/^[[:space:]]*(deb|# deb|deb-src|# deb-src)[[:space:]].*bullseye/ s|https?://mirrors\.aliyun\.com/debian-security|http://deb.debian.org/debian-security|g' "$path"
sed -i -E '/^[[:space:]]*(deb|# deb|deb-src|# deb-src)[[:space:]].*bullseye/ s|https?://[^[:space:]]+/debian-security|http://deb.debian.org/debian-security|g' "$path"
sed -i -E '/^[[:space:]]*(deb|# deb|deb-src|# deb-src)[[:space:]].*bullseye/ s|https?://mirrors\.ustc\.edu\.cn/debian|http://deb.debian.org/debian|g' "$path"
sed -i -E '/^[[:space:]]*(deb|# deb|deb-src|# deb-src)[[:space:]].*bullseye/ s|https?://mirrors\.aliyun\.com/debian|http://deb.debian.org/debian|g' "$path"
sed -i -E '/^[[:space:]]*(deb|# deb|deb-src|# deb-src)[[:space:]].*bullseye/ s|https?://[^[:space:]]+/debian|http://deb.debian.org/debian|g' "$path"
done < <(apt_source_list_files)
}
sanitize_apt_deb822_files() {
local path=""
local tmp=""
while IFS= read -r path; do
[[ -n "$path" ]] || continue
if ! grep -qiE '^[[:space:]]*Suites:[[:space:]].*bullseye' "$path"; then
log "APT sanitize: skipping non-Debian deb822 source ${path}"
continue
fi
tmp="$(mktemp)"
awk '
BEGIN { disabled = 0 }
/^[[:space:]]*Types:[[:space:]]*/ {
line = $0
sub(/^[[:space:]]*Types:[[:space:]]*/, "", line)
gsub(/deb-src/, "", line)
gsub(/[[:space:]]+/, " ", line)
sub(/^ /, "", line)
sub(/ $/, "", line)
if (line == "") {
print "Enabled: no"
disabled = 1
} else {
print "Types: " line
}
next
}
/^[[:space:]]*Suites:[[:space:]]*/ {
line = $0
sub(/^[[:space:]]*Suites:[[:space:]]*/, "", line)
gsub(/bullseye-backports/, "", line)
gsub(/[[:space:]]+/, " ", line)
sub(/^ /, "", line)
sub(/ $/, "", line)
if (line == "") {
if (!disabled) {
print "Enabled: no"
disabled = 1
}
} else {
print "Suites: " line
}
next
}
/^[[:space:]]*URIs:[[:space:]]*/ {
line = $0
gsub(/https?:\/\/mirrors\.ustc\.edu\.cn\/debian-security/, "http://deb.debian.org/debian-security", line)
gsub(/https?:\/\/mirrors\.aliyun\.com\/debian-security/, "http://deb.debian.org/debian-security", line)
gsub(/https?:\/\/[^[:space:]]+\/debian-security/, "http://deb.debian.org/debian-security", line)
gsub(/https?:\/\/mirrors\.ustc\.edu\.cn\/debian/, "http://deb.debian.org/debian", line)
gsub(/https?:\/\/mirrors\.aliyun\.com\/debian/, "http://deb.debian.org/debian", line)
gsub(/https?:\/\/[^[:space:]]+\/debian/, "http://deb.debian.org/debian", line)
print line
next
}
{ print }
' "$path" >"$tmp"
mv -f "$tmp" "$path"
done < <(apt_source_deb822_files)
}
sanitize_apt_sources() {
backup_apt_source_files
sanitize_apt_list_files
sanitize_apt_deb822_files
log "APT sanitize: deb-src disabled"
log "APT sanitize: bullseye-backports disabled"
log "APT sanitize: Debian mirrors normalized"
}
apt_update_once() {
apt-get clean
apt-get update
}
apt_update_with_recovery() {
if apt_update_once; then
return 0
fi
log "APT update failed, attempting recovery"
disable_apt_translations
sanitize_apt_sources
if apt_update_once; then
log "APT update recovered successfully"
return 0
fi
die "APT update failed after recovery"
}
strip_git_url_credentials() {
local url="$1"
printf '%s\n' "$url" | sed -E 's#^(https?://)[^/@]+@#\1#'
}
git_url_is_ssh() {
local url="$1"
[[ "$url" == git@* || "$url" == ssh://* ]]
}
git_url_is_http() {
local url="$1"
[[ "$url" == http://* || "$url" == https://* ]]
}
build_authenticated_git_url() {
GIT_AUTH_MODE="none"
GIT_EFFECTIVE_URL="$GIT_URL"
export GIT_TERMINAL_PROMPT=0
if git_url_is_ssh "$GIT_URL"; then
GIT_AUTH_MODE="ssh"
return 0
fi
if git_url_is_http "$GIT_URL" && [[ -n "$IOMATEX_GIT_TOKEN" ]]; then
GIT_AUTH_MODE="token"
GIT_EFFECTIVE_URL="$(printf '%s\n' "$GIT_URL" | sed -E "s#^(https?://)#\1${IOMATEX_GIT_TOKEN}@#")"
return 0
fi
}
run_git_command() {
local label="$1"
shift
local tmp_output=""
local rc=0
tmp_output="$(mktemp)"
set +e
"$@" >"$tmp_output" 2>&1
rc=$?
set -e
cat "$tmp_output"
if [[ "$rc" -ne 0 ]]; then
if [[ "$GIT_AUTH_MODE" == "none" ]] && git_url_is_http "$GIT_URL" && grep -Eqi 'could not read Username|terminal prompts disabled|authentication failed|fatal: Authentication failed|fatal: could not read Password' "$tmp_output"; then
rm -f "$tmp_output"
die "Git requires authentication. Use IOMATEX_GIT_TOKEN or SSH URL"
fi
rm -f "$tmp_output"
die "Git command failed during ${label}"
fi
rm -f "$tmp_output"
}
resolved_installer_path() {
if [[ "$SOURCE_TYPE" == "git" && -f "${PROJECT_DIR}/local_installer.sh" ]]; then
printf '%s\n' "${PROJECT_DIR}/local_installer.sh"
return 0
fi
printf '%s\n' "$SCRIPT_PATH"
}
record_source_metadata() {
set_state_value "INSTALLER_PATH" "$(resolved_installer_path)"
set_state_value "PROJECT_ROOT" "$PROJECT_DIR"
set_state_value "SOURCE_TYPE" "$SOURCE_TYPE"
set_state_value "SOURCE_DESCRIPTION" "$SOURCE_DESCRIPTION"
set_state_value "SOURCE_REPO_URL" "$SOURCE_REPO_URL"
set_state_value "SOURCE_BRANCH" "$SOURCE_BRANCH"
set_state_value "SOURCE_COMMIT" "$SOURCE_COMMIT"
}
save_selected_stages() {
local selected_csv
selected_csv="$(join_by_comma "${SELECTED_STAGES[@]}")"
set_state_value "SELECTED_STAGES" "$selected_csv"
}
stage_is_selected() {
local stage="$1"
in_array "$stage" "${SELECTED_STAGES[@]}"
}
stage_is_default_selected() {
local stage="$1"
in_array "$stage" "${MUST_HAVE_STAGES[@]}"
}
canonicalize_stage_list() {
local raw_items=("$@")
local stage
local item
local output=()
for item in "${raw_items[@]}"; do
[[ -n "$item" ]] || continue
is_known_stage "$item" || die "Unknown stage: ${item}"
done
for stage in "${STAGE_ORDER[@]}"; do
for item in "${raw_items[@]}"; do
if [[ "$item" == "$stage" ]] && ! in_array "$stage" "${output[@]}"; then
output+=("$stage")
fi
done
done
SELECTED_STAGES=("${output[@]}")
}
load_selected_stages_from_csv() {
local csv="$1"
local items=()
local item
if [[ -z "$csv" ]]; then
SELECTED_STAGES=()
return 0
fi
csv="${csv//,/ }"
for item in $csv; do
[[ -n "$item" ]] || continue
items+=("$item")
done
canonicalize_stage_list "${items[@]}"
}
use_default_stage_selection() {
SELECTED_STAGES=("${MUST_HAVE_STAGES[@]}")
}
use_all_stage_selection() {
SELECTED_STAGES=("${STAGE_ORDER[@]}")
}
toggle_stage_selection() {
local stage="$1"
local updated=()
local existing
if stage_is_selected "$stage"; then
for existing in "${SELECTED_STAGES[@]}"; do
[[ "$existing" == "$stage" ]] || updated+=("$existing")
done
SELECTED_STAGES=("${updated[@]}")
return 0
fi
updated=("${SELECTED_STAGES[@]}" "$stage")
canonicalize_stage_list "${updated[@]}"
}
stage_number_to_name() {
local token="$1"
case "$token" in
1) echo "stage_env" ;;
2) echo "stage_wifi" ;;
3) echo "stage_mqtt" ;;
4) echo "stage_z2m" ;;
5) echo "stage_ui" ;;
6) echo "stage_itscreen" ;;
7) echo "stage_reverse_tunnels" ;;
*) return 1 ;;
esac
}
print_stage_selection_menu() {
local index=0
local stage
local marker
local label
echo
echo "Available stages:"
for stage in "${STAGE_ORDER[@]}"; do
index=$((index + 1))
if stage_is_selected "$stage"; then
marker="Y"
else
marker="N"
fi
if stage_is_default_selected "$stage"; then
label="required / recommended"
else
label="optional"
fi
printf ' [%s] %d) %-22s (%s)\n' "$marker" "$index" "$stage" "$label"
done
echo
echo "Press Enter to continue with defaults."
echo "Or enter stage numbers/names to toggle, separated by space or comma."
echo "Special values: all, defaults, none"
}
prompt_for_stage_selection() {
local input=""
local token=""
local stage=""
use_default_stage_selection
while true; do
print_stage_selection_menu
read -r -p "Selection: " input || true
input="${input#"${input%%[![:space:]]*}"}"
input="${input%"${input##*[![:space:]]}"}"
if [[ -z "$input" ]]; then
break
fi
case "$input" in
all)
use_all_stage_selection
break
;;
defaults)
use_default_stage_selection
break
;;
none)
SELECTED_STAGES=()
break
;;
esac
input="${input//,/ }"
for token in $input; do
if stage="$(stage_number_to_name "$token" 2>/dev/null)"; then
toggle_stage_selection "$stage"
continue
fi
if is_known_stage "$token"; then
toggle_stage_selection "$token"
continue
fi
warn "Unknown selection token: ${token}"
stage=""
done
break
done
}
next_selected_stage_after() {
local current="$1"
local seen_current=0
local stage
for stage in "${STAGE_ORDER[@]}"; do
if [[ "$seen_current" -eq 0 ]]; then
[[ "$stage" == "$current" ]] && seen_current=1
continue
fi
stage_is_selected "$stage" || continue
printf '%s\n' "$stage"
return 0
done
return 1
}
resolve_resume_stage() {
local stage
local status
for stage in "${STAGE_ORDER[@]}"; do
stage_is_selected "$stage" || continue
if [[ "$stage" == "stage_env" ]]; then
status="$(get_stage_status "$stage")"
[[ "$status" == "success" ]] && continue
printf '%s\n' "$stage"
return 0
fi
status="$(get_stage_status "$stage")"
if [[ "$status" != "success" ]]; then
printf '%s\n' "$stage"
return 0
fi
done
return 1
}
install_post_reboot_unit() {
local installer_path
installer_path="$(get_state_value "INSTALLER_PATH")"
[[ -n "$installer_path" ]] || installer_path="$SCRIPT_PATH"
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=${PROJECT_DIR}
ExecStart=/bin/bash ${installer_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() {
local installer_path
installer_path="$(get_state_value "INSTALLER_PATH")"
[[ -n "$installer_path" ]] || installer_path="$SCRIPT_PATH"
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 ${installer_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_git_repo_dir() {
local path="$1"
git -C "$path" rev-parse --show-toplevel >/dev/null 2>&1
}
default_git_checkout_dir() {
if is_git_repo_dir "$SCRIPT_DIR"; then
printf '%s\n' "$SCRIPT_DIR"
else
printf '%s\n' "$IOMATEX_GIT_DIR"
fi
}
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
}
stage_candidates() {
local stage="$1"
case "$stage" in
stage_env)
printf '%s\n' "stage_env_install.sh"
printf '%s\n' "stage_env_install_no_pulse.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"
printf '%s\n' "stage_z2m.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
}
has_detectable_stage_installer() {
local path="$1"
local stage="$2"
local stage_dir="${path}/${stage}"
local candidate
[[ -d "$stage_dir" ]] || return 1
while IFS= read -r candidate; do
[[ -n "$candidate" ]] || continue
[[ -f "${stage_dir}/${candidate}" ]] && return 0
done < <(stage_candidates "$stage")
find "$stage_dir" -maxdepth 1 -type f \
\( -name '*_install.sh' -o -name '*_installer.sh' -o -name 'stage_*_install' -o -name 'stage_*_install.sh' \) \
| grep -q .
}
is_prod_root() {
local path="$1"
[[ -d "$path" ]] || return 1
[[ -d "$path/stage_env" ]] || return 1
has_detectable_stage_installer "$path" "stage_env"
}
resolve_prod_dir_from_path() {
local input="$1"
local abs_input=""
local extract_root=""
if [[ -d "$input" ]]; then
abs_input="$(resolve_abs_dir "$input")"
if is_prod_root "$abs_input"; then
SOURCE_TYPE="local_dir"
SOURCE_DESCRIPTION="$abs_input"
printf '%s\n' "$abs_input"
return 0
fi
if is_prod_root "$abs_input/Prod"; then
SOURCE_TYPE="local_dir"
SOURCE_DESCRIPTION="$abs_input/Prod"
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")"
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 "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 "Extracting archive ${abs_input} into ${extract_root}"
tar -xf "$abs_input" -C "$extract_root"
;;
esac
if is_prod_root "$extract_root/Prod"; then
SOURCE_TYPE="archive"
SOURCE_DESCRIPTION="$abs_input"
printf '%s\n' "$extract_root/Prod"
return 0
fi
return 1
}
ensure_git_available() {
if command -v git >/dev/null 2>&1; then
return 0
fi
log "git not found; installing git"
apt-get install -y git
}
prepare_git_source() {
local checkout_dir="$1"
local resolved_checkout=""
local current_remote=""
local expected_remote=""
local did_clone=0
build_authenticated_git_url
expected_remote="$(strip_git_url_credentials "$GIT_URL")"
log "Using git source:"
log " repo = ${expected_remote}"
log " branch = ${GIT_BRANCH}"
log " auth = ${GIT_AUTH_MODE}"
ensure_git_available
if [[ -e "$checkout_dir" && ! -d "$checkout_dir" ]]; then
die "Git checkout path exists but is not a directory: ${checkout_dir}"
fi
if [[ ! -d "$checkout_dir" ]]; then
mkdir -p "$(dirname "$checkout_dir")"
log "Cloning git repository ${expected_remote} (branch=${GIT_BRANCH}) into ${checkout_dir}"
run_git_command "clone" git clone --branch "$GIT_BRANCH" --single-branch "$GIT_EFFECTIVE_URL" "$checkout_dir"
git -C "$checkout_dir" remote set-url origin "$expected_remote"
did_clone=1
else
if ! is_git_repo_dir "$checkout_dir"; then
die "Existing path is not a git repository: ${checkout_dir}"
fi
current_remote="$(git -C "$checkout_dir" remote get-url origin 2>/dev/null || true)"
[[ -n "$current_remote" ]] || die "Git repository at ${checkout_dir} has no origin remote"
if [[ "$(strip_git_url_credentials "$current_remote")" != "$expected_remote" ]]; then
die "Git repository at ${checkout_dir} uses origin ${current_remote}, expected ${GIT_URL}"
fi
fi
resolved_checkout="$(resolve_abs_dir "$checkout_dir")"
SOURCE_TYPE="git"
SOURCE_DESCRIPTION="$resolved_checkout"
SOURCE_REPO_URL="$expected_remote"
SOURCE_BRANCH="$GIT_BRANCH"
if [[ "$did_clone" -eq 0 ]]; then
log "Updating git repository at ${resolved_checkout}"
if [[ "$GIT_EFFECTIVE_URL" != "$expected_remote" ]]; then
run_git_command "fetch" git -C "$resolved_checkout" -c "remote.origin.url=${GIT_EFFECTIVE_URL}" fetch --prune origin
else
run_git_command "fetch" git -C "$resolved_checkout" fetch --prune origin
fi
if git -C "$resolved_checkout" show-ref --verify --quiet "refs/heads/${GIT_BRANCH}"; then
run_git_command "checkout" git -C "$resolved_checkout" checkout "$GIT_BRANCH"
else
run_git_command "checkout" git -C "$resolved_checkout" checkout -B "$GIT_BRANCH" "origin/${GIT_BRANCH}"
fi
run_git_command "ff-only merge" git -C "$resolved_checkout" merge --ff-only "origin/${GIT_BRANCH}"
else
run_git_command "checkout" git -C "$resolved_checkout" checkout "$GIT_BRANCH"
fi
SOURCE_COMMIT="$(git -C "$resolved_checkout" rev-parse HEAD)"
SOURCE_BRANCH="$(git -C "$resolved_checkout" rev-parse --abbrev-ref HEAD)"
SOURCE_REPO_URL="$(strip_git_url_credentials "$(git -C "$resolved_checkout" remote get-url origin)")"
log "Git source ready: remote=${SOURCE_REPO_URL} branch=${SOURCE_BRANCH} commit=${SOURCE_COMMIT}"
PROJECT_DIR="$resolved_checkout"
}
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=""
local session_id=""
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
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"
}
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=()
SKIPPED_BY_SELECTION_STAGES=()
SKIPPED_MISSING_STAGES=()
FAILED_STAGES=()
for stage in "${STAGE_ORDER[@]}"; do
status="$(get_stage_status "$stage")"
case "$status" in
success)
SUCCESS_STAGES+=("$stage")
;;
skipped_by_selection)
SKIPPED_STAGES+=("$stage")
SKIPPED_BY_SELECTION_STAGES+=("$stage")
;;
skipped_stage_missing|skipped_installer_missing)
SKIPPED_STAGES+=("$stage")
SKIPPED_MISSING_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")
SKIPPED_MISSING_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")
SKIPPED_MISSING_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"
export IOMATEX_INSTALLER_NONINTERACTIVE="$NON_INTERACTIVE"
export IOMATEX_INSTALLER_SELECTED_STAGES="$(join_by_comma "${SELECTED_STAGES[@]}")"
export UCF_FORCE_CONFFOLD=1
/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_header() {
echo
echo "============================================================"
echo "IOMATEX LOCAL INSTALLER"
echo "============================================================"
echo "Source type : ${SOURCE_TYPE}"
echo "Source : ${SOURCE_DESCRIPTION}"
if [[ "$SOURCE_TYPE" == "git" ]]; then
echo "Repo URL : ${SOURCE_REPO_URL}"
echo "Branch : ${SOURCE_BRANCH}"
echo "Commit : ${SOURCE_COMMIT}"
fi
echo "Project root : ${PROJECT_DIR}"
echo "Interactive mode : ${INTERACTIVE_MODE}"
echo "Selected stages : ${SELECTED_STAGES:+$(join_by_space "${SELECTED_STAGES[@]}")}"
if [[ "${#SELECTED_STAGES[@]}" -eq 0 ]]; then
echo "Selected stages : none"
fi
echo "Log file : ${LOG_FILE}"
echo "State file : ${STATE_FILE}"
echo "============================================================"
echo
}
print_summary() {
local stage
local status
echo
echo "============================================================"
echo "LOCAL INSTALLER SUMMARY"
echo "============================================================"
echo "Source type : ${SOURCE_TYPE}"
echo "Source : ${SOURCE_DESCRIPTION}"
if [[ -n "$SOURCE_REPO_URL" ]]; then
echo "Repo URL : ${SOURCE_REPO_URL}"
fi
if [[ -n "$SOURCE_BRANCH" ]]; then
echo "Branch : ${SOURCE_BRANCH}"
fi
if [[ -n "$SOURCE_COMMIT" ]]; then
echo "Current commit : ${SOURCE_COMMIT}"
fi
echo "Project root : ${PROJECT_DIR}"
echo "Selected stages : ${SELECTED_STAGES:+$(join_by_space "${SELECTED_STAGES[@]}")}"
if [[ "${#SELECTED_STAGES[@]}" -eq 0 ]]; then
echo "Selected stages : none"
fi
echo "Reboot continuation : $([[ "$REBOOT_CONTINUATION_USED" -eq 1 ]] && echo yes || echo no)"
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
echo " - ${stage}"
done
fi
echo
echo "Skipped by selection:"
if [[ "${#SKIPPED_BY_SELECTION_STAGES[@]}" -eq 0 ]]; then
echo " - none"
else
for stage in "${SKIPPED_BY_SELECTION_STAGES[@]}"; do
echo " - ${stage}"
done
fi
echo
echo "Skipped because missing:"
if [[ "${#SKIPPED_MISSING_STAGES[@]}" -eq 0 ]]; then
echo " - none"
else
for stage in "${SKIPPED_MISSING_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)"
;;
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 followed by an automatic reboot only when it is selected and succeeds"
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 "============================================================"
}
while [[ $# -gt 0 ]]; do
case "$1" in
--git)
USE_GIT_SOURCE=1
shift
;;
--git-url)
[[ $# -ge 2 ]] || die "--git-url requires a value"
USE_GIT_SOURCE=1
GIT_URL="$2"
shift 2
;;
--branch)
[[ $# -ge 2 ]] || die "--branch requires a value"
USE_GIT_SOURCE=1
GIT_BRANCH="$2"
shift 2
;;
--non-interactive)
NON_INTERACTIVE=1
shift
;;
--with-optional-all)
WITH_OPTIONAL_ALL=1
shift
;;
--only)
[[ $# -ge 2 ]] || die "--only requires a comma-separated stage list"
ONLY_STAGES_RAW="$2"
shift 2
;;
--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
if [[ "$WITH_OPTIONAL_ALL" -eq 1 && -n "$ONLY_STAGES_RAW" ]]; then
die "--with-optional-all and --only cannot be used together"
fi
if [[ -n "$SOURCE_PATH" && "$USE_GIT_SOURCE" -eq 1 ]]; then
die "Explicit source path cannot be combined with --git/--git-url/--branch"
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 [[ "$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
PROJECT_DIR="$(get_state_value "PROJECT_ROOT")"
[[ -n "$PROJECT_DIR" ]] || die "Post-reboot continuation requested but PROJECT_ROOT is missing from state"
SOURCE_TYPE="$(get_state_value "SOURCE_TYPE")"
SOURCE_DESCRIPTION="$(get_state_value "SOURCE_DESCRIPTION")"
SOURCE_REPO_URL="$(get_state_value "SOURCE_REPO_URL")"
SOURCE_BRANCH="$(get_state_value "SOURCE_BRANCH")"
SOURCE_COMMIT="$(get_state_value "SOURCE_COMMIT")"
load_selected_stages_from_csv "$(get_state_value "SELECTED_STAGES")"
REBOOT_CONTINUATION_USED=1
INTERACTIVE_MODE="resume-post-reboot"
else
log "Running APT preflight"
disable_apt_translations
apt_update_with_recovery
if [[ -n "$SOURCE_PATH" ]]; then
PROJECT_DIR="$(resolve_prod_dir_from_path "$SOURCE_PATH" || true)"
[[ -n "$PROJECT_DIR" ]] || die "Failed to resolve Prod from source: ${SOURCE_PATH}"
SOURCE_REPO_URL=""
SOURCE_BRANCH=""
SOURCE_COMMIT=""
else
USE_GIT_SOURCE=1
prepare_git_source "$(default_git_checkout_dir)"
fi
if [[ "$NON_INTERACTIVE" -eq 1 ]]; then
INTERACTIVE_MODE="non-interactive"
elif [[ "$ORIG_STDIN_IS_TTY" -ne 1 || "$ORIG_STDOUT_IS_TTY" -ne 1 ]]; then
NON_INTERACTIVE=1
INTERACTIVE_MODE="non-interactive(auto)"
else
INTERACTIVE_MODE="interactive"
fi
if [[ -n "$ONLY_STAGES_RAW" ]]; then
load_selected_stages_from_csv "$ONLY_STAGES_RAW"
NON_INTERACTIVE=1
INTERACTIVE_MODE="explicit-selection"
elif [[ "$WITH_OPTIONAL_ALL" -eq 1 ]]; then
use_all_stage_selection
NON_INTERACTIVE=1
INTERACTIVE_MODE="non-interactive(all-stages)"
elif [[ "$NON_INTERACTIVE" -eq 1 ]]; then
use_default_stage_selection
else
prompt_for_stage_selection
fi
fi
[[ -d "$PROJECT_DIR" ]] || die "Project root does not exist: ${PROJECT_DIR}"
if [[ "${#SELECTED_STAGES[@]}" -eq 0 && "$RESUME_POST_REBOOT" -eq 1 ]]; then
warn "No selected stages were found in state; nothing to resume"
fi
if [[ -n "$FROM_STAGE" && "${#SELECTED_STAGES[@]}" -gt 0 ]] && ! stage_is_selected "$FROM_STAGE"; then
die "--from stage ${FROM_STAGE} is not part of the selected stage set"
fi
record_source_metadata
save_selected_stages
set_state_value "INTERACTIVE_MODE" "$INTERACTIVE_MODE"
set_state_value "REBOOT_CONTINUATION_USED" "$REBOOT_CONTINUATION_USED"
log "Project root: ${PROJECT_DIR}"
if [[ "$SOURCE_TYPE" == "git" ]]; then
log "Git metadata: remote=${SOURCE_REPO_URL} branch=${SOURCE_BRANCH} commit=${SOURCE_COMMIT}"
fi
log "Selected stages: ${SELECTED_STAGES:+$(join_by_space "${SELECTED_STAGES[@]}")}"
if [[ "${#SELECTED_STAGES[@]}" -eq 0 ]]; then
log "Selected stages: none"
fi
print_header
if [[ "$RESUME_POST_REBOOT" -eq 1 ]]; then
FROM_STAGE="${FROM_STAGE:-$(resolve_resume_stage || true)}"
if [[ -z "$FROM_STAGE" ]]; then
log "No remaining selected stages after reboot; cleaning continuation state"
cleanup_post_reboot_unit
record_summary_from_state
print_summary
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
for stage in "${STAGE_ORDER[@]}"; do
if ! stage_is_selected "$stage"; then
if [[ "$(get_stage_status "$stage")" != "success" ]]; then
set_stage_status "$stage" "skipped_by_selection"
fi
fi
done
STARTED=0
RUN_FAILED=0
for stage in "${STAGE_ORDER[@]}"; do
local_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 ! stage_is_selected "$stage"; then
log "SKIP: ${stage} skipped_by_selection"
SKIPPED_STAGES+=("$stage")
SKIPPED_BY_SELECTION_STAGES+=("$stage")
continue
fi
if [[ -z "$FROM_STAGE" && "$local_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_selected_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"
set_state_value "REBOOT_CONTINUATION_USED" "1"
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
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