set -euo pipefail umask 077 export GIT_TERMINAL_PROMPT=0 state=/var/lib/seiugw-updater repo="$SEIUGW_UPDATE_REPO" profile=/nix/var/nix/profiles/system database="$SEIUGW_UPDATE_DATA/seiugw.db" gateway_units=(seiugw.service seiugw-bacnet.service) commit="" previous_commit="" target="" step="Vorprüfung" checkout_changed=0 services_stopped=0 activation_started=0 snapshot_ready=0 exec 9>"$state/lock" flock -n 9 work=$(mktemp -d "$state/run.XXXXXX") cd "$work" git_gateway() { git -C "$repo" -c core.hooksPath=/dev/null "$@" } status() { jq -n --arg phase "$1" --arg message "$2" --arg commit "$commit" --arg target "$target" \ --arg updatedAt "$(date --iso-8601=seconds)" --arg runId "${work##*/}" \ '{phase:$phase,message:$message,commit:$commit,target:$target,updatedAt:$updatedAt,runId:$runId}' >"$work/status.json" chmod 0644 "$work/status.json" mv -f "$work/status.json" "$state/status.json" } healthy() { local attempt consecutive=0 heartbeat now for ((attempt=0; attempt<30; attempt++)); do now=$(date +%s%3N) heartbeat=$(runuser -u seiugw -- sqlite3 -readonly -cmd '.timeout 1000' "$database" \ 'SELECT heartbeat_ms FROM bacnet_runtime WHERE id=1' 2>/dev/null) || heartbeat="" if systemctl is-active --quiet seiugw.service && systemctl is-active --quiet seiugw-bacnet.service && [[ $heartbeat =~ ^[0-9]{13}$ ]] && ((now - heartbeat < 5000)) && curl -fsS --max-time 2 "$SEIUGW_UPDATE_HEALTH/api/health" | jq -e '.status == "ok" and .adminConfigured == true' >/dev/null && curl -fsS --max-time 2 "$SEIUGW_UPDATE_HEALTH/" -o /dev/null; then ((consecutive+=1)) if ((consecutive >= 3)); then return 0; fi else consecutive=0 fi sleep 2 done return 1 } finish() { local code=$? restored=1 trap - EXIT trap '' HUP INT TERM if ((code != 0)); then echo "Gateway update failed during $step (exit $code)." >&2 if ((checkout_changed || services_stopped)); then status rollingBack "Fehler bei $step. Die vorherige Version wird wiederhergestellt." || true if ((services_stopped)); then if systemctl stop "${gateway_units[@]}"; then if ((snapshot_ready)); then runuser -u seiugw -- sqlite3 -bail "$database" ".restore '$work/gateway.db'" || restored=0 fi else restored=0 fi fi if ((checkout_changed)); then git_gateway reset --keep "$previous_commit" || restored=0; fi commit=$previous_commit if ((activation_started)); then if [[ $(readlink -f "$profile") != "$previous_system" ]]; then nix-env --profile "$profile" --set "$previous_system" || restored=0 fi "$previous_system/bin/switch-to-configuration" switch || restored=0 fi if ((services_stopped)); then if ! systemctl start "${gateway_units[@]}" || ! healthy; then restored=0; fi fi if ((restored)); then status rolledBack "Fehler bei $step. Die vorherige Version wurde wiederhergestellt." || true else status rollbackFailed "Fehler bei $step. Die Wiederherstellung konnte nicht bestätigt werden." || true echo "Recovery files kept in $work." >&2 exit "$code" fi else status failed "Fehler bei $step. Die installierte Version läuft weiter." || true fi fi rm -f -- "$work/result" "$work/gateway.db" "$work/gateway.db-wal" "$work/gateway.db-shm" "$work/status.json" rmdir -- "$work" exit "$code" } trap finish EXIT trap 'exit 130' HUP INT TERM status checking "Der Repository- und Systemstand wird geprüft." [[ $(git_gateway rev-parse --show-toplevel) == "$repo" ]] commit=$(git_gateway rev-parse HEAD) previous_commit=$commit [[ $(git_gateway symbolic-ref --short HEAD) == "$SEIUGW_UPDATE_BRANCH" ]] [[ -z $(git_gateway status --porcelain --untracked-files=all) ]] previous_system=$(readlink -f /run/current-system) [[ $(readlink -f "$profile") == "$previous_system" ]] step="Git-Abruf" status fetching "Neue Version wird aus Git abgerufen." timeout 120 git -C "$repo" -c core.hooksPath=/dev/null -c credential.helper= \ fetch --no-tags -- "$SEIUGW_UPDATE_REMOTE" "refs/heads/$SEIUGW_UPDATE_BRANCH" target=$(git_gateway rev-parse FETCH_HEAD) if [[ $commit == "$target" ]]; then status current "Das Gateway ist bereits auf dem aktuellen Stand." exit 0 fi if git_gateway merge-base --is-ancestor "$target" "$commit"; then status unpublished "Die installierte Version ist neuer als der veröffentlichte Stand." exit 0 fi git_gateway merge-base --is-ancestor "$commit" "$target" step="Systembau" status building "Die neue NixOS-Generation wird gebaut." checkout_changed=1 git_gateway merge --ff-only "$target" timeout --kill-after=30s 60m nixos-rebuild build candidate=$(readlink -f result) [[ -x $candidate/bin/switch-to-configuration ]] step="Datenbanksicherung" status activating "Das Gateway wird kurz angehalten. Die Datenbank wird gesichert." services_stopped=1 systemctl stop "${gateway_units[@]}" [[ -f $database ]] chgrp seiugw "$work" chmod 0710 "$work" install -o seiugw -g seiugw -m 0600 /dev/null "$work/gateway.db" runuser -u seiugw -- sqlite3 -bail "$database" ".backup '$work/gateway.db'" [[ $(sqlite3 -bail "$work/gateway.db" 'PRAGMA quick_check') == ok ]] snapshot_ready=1 step="Aktivierung" status activating "Die neue Version wird aktiviert und geprüft." activation_started=1 "$candidate/bin/switch-to-configuration" test [[ $(readlink -f /run/current-system) == "$candidate" ]] systemctl restart "${gateway_units[@]}" step="Funktionsprüfung" healthy step="Boot-Konfiguration" nix-env --profile "$profile" --set "$candidate" "$candidate/bin/switch-to-configuration" boot [[ $(readlink -f "$profile") == "$candidate" ]] commit=$target status succeeded "Die neue Version ist aktiv und für den nächsten Start eingestellt."