ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(installer): atomic blue/green updates, pre-flight checks, offline support, pre-built releases
Juan Denis3f37994f1820
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 274837b9..5a124cae 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -105,11 +105,13 @@ jobs:BUILD_ARCH: ${{ matrix.arch }}run: bash scripts/build-release.sh- - name: Upload tarball artifact+ - name: Upload release artifactsuses: actions/upload-artifact@v4with:- name: serverkit-tarball-${{ matrix.arch }}- path: serverkit-*.tar.gz+ name: serverkit-release-${{ matrix.arch }}+ path: |+ serverkit-*.tar.gz+ checksums.txtif-no-files-found: errorbuild-docker:@@ -159,22 +161,24 @@ jobs:- name: Checkout codeuses: actions/checkout@v4- - name: Download release tarballs+ - name: Download release artifactsuses: actions/download-artifact@v4with:- path: release-tarballs- pattern: serverkit-tarball-*+ path: release-artifacts+ pattern: serverkit-release-*merge-multiple: true- - name: Generate checksums for tracked release files+ - name: Assemble release filesrun: |mkdir -p releasecp VERSION release/VERSIONcp docker-compose.yml release/docker-compose.ymlcp Dockerfile release/Dockerfile- mv release-tarballs/serverkit-*.tar.gz release/ 2>/dev/null || true+ mv release-artifacts/serverkit-*.tar.gz release/ 2>/dev/null || true+ mv release-artifacts/checksums.txt release/checksums.txt 2>/dev/null || truecd release- sha256sum * > checksums.txt+ sha256sum serverkit-*.tar.gz >> checksums.txt+ sort -u checksums.txt -o checksums.txtcat checksums.txt- name: Create GitHub Releasediff --git a/README.md b/README.mdindex 943711f0..b57c0519 100644--- a/README.md+++ b/README.md@@ -363,6 +363,18 @@ curl -fsSL https://serverkit.ai/install.sh | bash```> Works on Ubuntu 22.04+, Debian 12+, Fedora, and RHEL/Rocky/AlmaLinux 9+. Sets up everything automatically.+>+> Optional: `PANEL_DOMAIN=panel.example.com` sets the domain and tries Let's Encrypt; `SERVERKIT_OFFLINE_TARBALL=...` installs from a local tarball.++### Update++```bash+sudo serverkit update+```++Atomic blue/green update with pre-flight checks, DB backup, migration, and+automatic rollback. Use `--dry-run` to preview, `--branch dev` for dev builds,+or `--release [version]` for release tarballs.### Option 2: Dockerdiff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.mdindex 03896ba2..98f2c782 100644--- a/docs/INSTALLATION.md+++ b/docs/INSTALLATION.md@@ -11,6 +11,71 @@ To connect additional servers to this panel, install the agent — see the[serverkit-agent README](https://github.com/jhd3197/serverkit-agent/blob/main/README.md)and [pairing.md](pairing.md). ServerKit is a modern server management panel for managing web applications, databases, Docker containers, and more.+## One-Line Install (Recommended)++```bash+curl -fsSL https://serverkit.ai/install.sh | sudo bash+```++The installer provisions Python, Docker, Nginx, SSL (best-effort), and systemd+services automatically. It uses an atomic blue/green layout: `/opt/serverkit` is+a symlink to either `/opt/serverkit-a` or `/opt/serverkit-b`, so failed updates+can roll back instantly.++### Install options++| Variable | Purpose |+|----------|---------|+| `PANEL_DOMAIN=panel.example.com` | Set the panel domain and attempt Let's Encrypt |+| `SERVERKIT_SKIP_SSL=1` | Skip HTTPS/certbot entirely |+| `INSTALL_FROM_RELEASE=1` | Install from the latest GitHub release tarball instead of cloning source |+| `SERVERKIT_VERSION=v1.7.0` | Pin a specific release version |+| `SERVERKIT_OFFLINE_TARBALL=/path/to/...tar.gz` | Use a local tarball instead of downloading |+| `SERVERKIT_MIRROR_URL=https://mirror.example.com/releases` | Fetch releases/checksums from a private mirror |++Example with a domain:++```bash+curl -fsSL https://serverkit.ai/install.sh | sudo PANEL_DOMAIN=panel.example.com bash+```++Example offline install:++```bash+curl -fsSL https://serverkit.ai/install.sh | \+ sudo SERVERKIT_OFFLINE_TARBALL=/tmp/serverkit-v1.7.0-linux-amd64.tar.gz bash+```++## Updating ServerKit++```bash+sudo serverkit update+```++The updater runs pre-flight checks, backs up the database, deploys into the+inactive blue/green slot, runs `flask db upgrade`, switches the symlink+atomically, and performs a health check. If the health check fails, it rolls+back to the previous slot automatically.++### Update options++```bash+sudo serverkit update --dry-run # preview changes without applying+sudo serverkit update --force # force update even if already current+sudo serverkit update --branch dev # update from a git branch+sudo serverkit update --release # update to the latest release+sudo serverkit update --release v1.7.0 # pin a release+```++Offline and mirror updates are also supported:++```bash+sudo SERVERKIT_OFFLINE_TARBALL=/tmp/serverkit-v1.7.0-linux-amd64.tar.gz \+ serverkit update --release++sudo SERVERKIT_MIRROR_URL=https://mirror.example.com/releases serverkit update+```+## Table of Contents- [Requirements](#requirements)diff --git a/install.sh b/install.shindex 499ee8bb..926c3729 100644--- a/install.sh+++ b/install.sh@@ -19,8 +19,13 @@ set -euo pipefail# ---------------------------------------------------------------------------# Settings and environment contract# ----------------------------------------------------------------------------INSTALL_DIR="/opt/serverkit"-VENV_DIR="$INSTALL_DIR/venv"+SERVERKIT_DIR="${SERVERKIT_DIR:-/opt/serverkit}"+INSTALL_DIR="$SERVERKIT_DIR"+BASE_NAME="$(basename "$INSTALL_DIR")"+BASE_DIR="$(dirname "$INSTALL_DIR")"+DIR_A="$BASE_DIR/${BASE_NAME}-a"+DIR_B="$BASE_DIR/${BASE_NAME}-b"+VENV_DIR="${SERVERKIT_VENV_DIR:-$INSTALL_DIR/venv}"LOG_DIR="/var/log/serverkit"DATA_DIR="/var/lib/serverkit"BACKUP_DIR="/var/backups/serverkit"@@ -40,6 +45,8 @@ CHANNEL="${CHANNEL:-Stable}"PANEL_DOMAIN="${PANEL_DOMAIN:-}"PANEL_PORT="${PANEL_PORT:-80}"SERVERKIT_SKIP_SSL="${SERVERKIT_SKIP_SSL:-0}"+SERVERKIT_OFFLINE_TARBALL="${SERVERKIT_OFFLINE_TARBALL:-}"+SERVERKIT_MIRROR_URL="${SERVERKIT_MIRROR_URL:-}"# Runtime state populated as we go (declared up-front for `set -u`).OS_FAMILY="unknown"@@ -48,6 +55,7 @@ DL_ARCH=""PKG_MGR=""SAFE_MODE=falseSSL_MODE="insecure"+FIRST_SLOT="$DIR_A"# ---------------------------------------------------------------------------# Terminal styling@@ -405,46 +413,69 @@ resolve_release_tag() {fetch_release() {phase "Downloading Pre-built Release"- local tag; tag=$(resolve_release_tag)- if [ -z "$tag" ]; then- warn "Latest release tag unknown — falling back to a source build."- INSTALL_FROM_RELEASE=0- return 1- fi- good "Latest release: $tag"+ local tag tarball tmp_dir unpacked- local base="https://github.com/${GITHUB_REPO}/releases/download/${tag}"- local tarball="/tmp/serverkit-${tag}-linux-${DL_ARCH}.tar.gz"+ if [ -n "$SERVERKIT_OFFLINE_TARBALL" ]; then+ [ -f "$SERVERKIT_OFFLINE_TARBALL" ] || halt "Offline tarball not found: $SERVERKIT_OFFLINE_TARBALL"+ tag="offline"+ tarball="$SERVERKIT_OFFLINE_TARBALL"+ good "Using offline tarball: $tarball"+ else+ tag=$(resolve_release_tag)+ if [ -z "$tag" ]; then+ warn "Latest release tag unknown — falling back to a source build."+ INSTALL_FROM_RELEASE=0+ return 1+ fi+ good "Latest release: $tag"- step "Fetching release tarball (${DL_ARCH})..."- if ! curl -sfL "${base}/serverkit-${tag}-linux-${DL_ARCH}.tar.gz" -o "$tarball"; then- warn "No release tarball for this platform — falling back to source."- INSTALL_FROM_RELEASE=0- return 1+ local base+ if [ -n "$SERVERKIT_MIRROR_URL" ]; then+ base="$SERVERKIT_MIRROR_URL"+ else+ base="https://github.com/${GITHUB_REPO}/releases/download/${tag}"+ fi++ tarball="/tmp/serverkit-${tag}-linux-${DL_ARCH}.tar.gz"+ step "Fetching release tarball (${DL_ARCH})..."+ if ! curl -sfL "${base}/serverkit-${tag}-linux-${DL_ARCH}.tar.gz" -o "$tarball"; then+ warn "No release tarball for this platform — falling back to source."+ INSTALL_FROM_RELEASE=0+ return 1+ fi++ step "Verifying checksum..."+ if curl -sfL "${base}/checksums.txt" -o "/tmp/serverkit-checksums-${tag}.txt"; then+ if ! (cd /tmp && sha256sum -c <(grep "serverkit-${tag}-linux-${DL_ARCH}.tar.gz" "serverkit-checksums-${tag}.txt") >/dev/null 2>&1); then+ halt "Checksum verification failed for release tarball."+ fi+ good "Checksum verified"+ else+ warn "Could not download checksums.txt — skipping verification"+ fifistep "Unpacking release..."- rm -rf "$INSTALL_DIR"- mkdir -p "$(dirname "$INSTALL_DIR")"- tar xzf "$tarball" -C "$(dirname "$INSTALL_DIR")"- rm -f "$tarball"+ tmp_dir="$(mktemp -d)"+ tar xzf "$tarball" -C "$tmp_dir"- # Normalize tarball layout: older archives have serverkit/ at root,- # newer ones have opt/serverkit/.- UNPACKED_DIR="$(dirname "$INSTALL_DIR")/serverkit"- if [ ! -d "$UNPACKED_DIR" ]; then- UNPACKED_DIR="$(dirname "$INSTALL_DIR")/opt/serverkit"- fi- if [ ! -d "$UNPACKED_DIR" ]; then- UNPACKED_DIR=$(find "$(dirname "$INSTALL_DIR")" -maxdepth 2 -type d -name serverkit | head -n1)- fi- [ -d "$UNPACKED_DIR" ] || halt "Release tarball layout is unrecognized (expected serverkit/ or opt/serverkit/)."- if [ "$UNPACKED_DIR" != "$INSTALL_DIR" ]; then- mv "$UNPACKED_DIR" "$INSTALL_DIR"+ unpacked="$tmp_dir/serverkit"+ [ ! -d "$unpacked" ] && unpacked="$tmp_dir/opt/serverkit"+ if [ ! -d "$unpacked" ]; then+ unpacked="$(find "$tmp_dir" -maxdepth 2 -type d -name serverkit | head -n1)"fi+ [ -d "$unpacked" ] || halt "Release tarball layout is unrecognized (expected serverkit/ or opt/serverkit/)."++ ensure_install_layout+ rm -rf "$FIRST_SLOT"+ cp -a "$unpacked" "$FIRST_SLOT"+ rm -rf "$tmp_dir"++ [ -L "$INSTALL_DIR" ] || ln -s "$FIRST_SLOT" "$INSTALL_DIR"+chmod +x "$INSTALL_DIR/serverkit"chmod +x "$INSTALL_DIR/scripts/"*.sh 2>/dev/null || true- good "Release unpacked into $INSTALL_DIR"+ good "Release unpacked into $FIRST_SLOT"}# ---------------------------------------------------------------------------@@ -453,9 +484,11 @@ fetch_release() {sync_source() {phase "Source Code"- if [ -d "$INSTALL_DIR/.git" ]; then+ ensure_install_layout++ if [ -d "$FIRST_SLOT/.git" ]; thenstep "Refreshing the existing checkout..."- cd "$INSTALL_DIR"+ cd "$FIRST_SLOT"if ! git pull --ff-only; thenwarn "Fast-forward failed (local edits?) — hard-resetting to origin/main."git fetch origin@@ -463,19 +496,35 @@ sync_source() {fielsestep "Cloning ServerKit..."- rm -rf "$INSTALL_DIR"- git clone --depth 1 "https://github.com/${GITHUB_REPO}.git" "$INSTALL_DIR"- cd "$INSTALL_DIR"+ rm -rf "$FIRST_SLOT"+ git clone --depth 1 "https://github.com/${GITHUB_REPO}.git" "$FIRST_SLOT"+ cd "$FIRST_SLOT"fi+ [ -L "$INSTALL_DIR" ] || ln -sfn "$FIRST_SLOT" "$INSTALL_DIR"good "Repository ready."}# ----------------------------------------------------------------------------# On-disk layout+# On-disk layout (blue/green slots + symlink)# ---------------------------------------------------------------------------+ensure_install_layout() {+ # Migrate legacy real-directory installs into the blue/green layout.+ if [ -d "$INSTALL_DIR" ] && [ ! -L "$INSTALL_DIR" ]; then+ step "Migrating to blue/green install layout..."+ mv "$INSTALL_DIR" "$FIRST_SLOT"+ ln -s "$FIRST_SLOT" "$INSTALL_DIR"+ good "Active install is now $INSTALL_DIR → $FIRST_SLOT"+ fi++ mkdir -p "$DIR_A" "$DIR_B"+ [ -L "$INSTALL_DIR" ] || ln -s "$FIRST_SLOT" "$INSTALL_DIR"+}+make_directories() {phase "Creating Directories"+ ensure_install_layout+local dfor d in "$LOG_DIR" "$DATA_DIR" "$BACKUP_DIR" "$CONFIG_DIR" "$INSTALL_DIR/backend/instance"; domkdir -p -m 0750 "$d"@@ -494,8 +543,20 @@ make_directories() {build_virtualenv() {phase "Python Environment"+ # If the release shipped a pre-built venv at the expected path, use it.+ if [ "$INSTALL_FROM_RELEASE" = "1" ] && [ -f "$FIRST_SLOT/venv/bin/activate" ] && [ -x "$FIRST_SLOT/venv/bin/python" ]; then+ step "Using pre-built virtual environment from release..."+ rm -rf "$VENV_DIR"+ cp -a "$FIRST_SLOT/venv" "$VENV_DIR"+ good "Virtual environment installed from release."+ return+ fi+step "Creating the virtual environment..."$PYTHON_BIN -m venv "$VENV_DIR"+ if [ ! -f "$VENV_DIR/bin/activate" ]; then+ halt "Virtual environment creation failed: $VENV_DIR/bin/activate not found."+ fisource "$VENV_DIR/bin/activate"step "Installing Python dependencies..."@@ -822,10 +883,12 @@ revert_install() {systemctl stop serverkit 2>/dev/null || truesystemctl stop nginx 2>/dev/null || true- if [ -d "$INSTALL_DIR.backup" ]; then- rm -rf "$INSTALL_DIR"- mv "$INSTALL_DIR.backup" "$INSTALL_DIR"- warn "Restored the previous installation from backup."+ local active+ active="$(readlink -f "$INSTALL_DIR" 2>/dev/null || echo "$INSTALL_DIR")"+ if [ -d "$active.backup" ]; then+ rm -rf "$active"+ cp -a "$active.backup" "$active"+ warn "Restored the previous installation from $active.backup"fisystemctl daemon-reload@@ -856,10 +919,12 @@ await_health() {# Safety copy of an existing install before we touch it# ---------------------------------------------------------------------------snapshot_existing() {- if [ -d "$INSTALL_DIR" ] && [ ! -d "$INSTALL_DIR.backup" ]; then+ local active+ active="$(readlink -f "$INSTALL_DIR" 2>/dev/null || echo "$INSTALL_DIR")"+ if [ -d "$active" ] && [ ! -d "$active.backup" ]; thenstep "Backing up the existing installation..."- cp -a "$INSTALL_DIR" "$INSTALL_DIR.backup"- good "Backup saved to $INSTALL_DIR.backup"+ cp -a "$active" "$active.backup"+ good "Backup saved to $active.backup"fi}@@ -971,9 +1036,9 @@ main() {build_frontendelsemake_directories- # Always build the virtualenv locally. Release tarballs no longer ship a- # pre-built venv because absolute shebangs/paths in a relocated venv- # break on the target machine (e.g. 203/EXEC from systemd).+ # Release tarballs now ship a pre-built, relocatable venv. If one is+ # present, build_virtualenv will use it; otherwise it falls back to a+ # local build.provision_pythonbuild_virtualenvfidiff --git a/scripts/build-release.sh b/scripts/build-release.shindex 2f590fd1..c5d0504b 100644--- a/scripts/build-release.sh+++ b/scripts/build-release.sh@@ -2,10 +2,14 @@## ServerKit release builder.#-# Produces a portable tarball that installs without compiling the frontend on-# the target: the full /opt/serverkit tree with a built frontend. The Python-# virtualenv is created locally by install.sh/update.sh so absolute paths in-# the venv always match the target machine.+# Produces a portable tarball that installs without compiling the frontend or+# building a Python venv on the target. The release contains:+# - /opt/serverkit source tree+# - /opt/serverkit/frontend/dist pre-built bundle+# - /opt/serverkit/venv pre-built Python virtual environment+#+# The venv is built locally and then made relocatable by rewriting absolute+# paths so it works at /opt/serverkit/venv on the target machine.## bash scripts/build-release.sh# VERSION=v1.7.0 bash scripts/build-release.sh@@ -13,6 +17,7 @@set -euo pipefailBUILD_DIR="/tmp/serverkit-release-build"+TARGET_VENV_PATH="/opt/serverkit/venv"# ---------------------------------------------------------------------------# Terminal styling (violet ServerKit identity, degrades to plain text)@@ -51,12 +56,14 @@ case "${BUILD_ARCH:-$(uname -m)}" inesacOUTPUT="serverkit-${RELEASE_TAG}-linux-${DL_ARCH}.tar.gz"+CHECKSUMS="checksums.txt"step "Building release ${RELEASE_TAG} for ${DL_ARCH}"# ---------------------------------------------------------------------------# Toolchain check# ---------------------------------------------------------------------------command -v node &>/dev/null || halt "Node.js is required."+python3 -c 'import venv' 2>/dev/null || halt "Python venv module is required."# ---------------------------------------------------------------------------# Stage a clean copy of the repository@@ -70,9 +77,31 @@ REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"# Copy the source tree with tar, which handles broken symlinks and avoids# the long rm -rf timeouts that cp + rm can hit on Windows/Git Bash.-mkdir -p "$BUILD_DIR"cd "$REPO_ROOT"-tar -cf - --exclude='./.git' --exclude='./node_modules' --exclude='./venv' --exclude='./.venv' --exclude='./.venv-wsl' --exclude='./backend/venv' --exclude='./backend/.venv' --exclude='./backend/.venv-wsl' --exclude='./__pycache__' --exclude='./.pytest_cache' --exclude='./instance' --exclude='./dist' --exclude='./backups' --exclude='./backend/dev-data/backups' --exclude='./backend/instance/backups' --exclude='./scripts/test/output' --exclude='*.png' --exclude='*.jpeg' --exclude='*.jpg' --exclude='*.log' --exclude='*.tmp' --exclude='*.pyc' . | tar -C "$BUILD_DIR" -xf -+tar -cf - \+ --exclude='./.git' \+ --exclude='./node_modules' \+ --exclude='./venv' \+ --exclude='./.venv' \+ --exclude='./.venv-wsl' \+ --exclude='./backend/venv' \+ --exclude='./backend/.venv' \+ --exclude='./backend/.venv-wsl' \+ --exclude='./__pycache__' \+ --exclude='./.pytest_cache' \+ --exclude='./instance' \+ --exclude='./dist' \+ --exclude='./backups' \+ --exclude='./backend/dev-data/backups' \+ --exclude='./backend/instance/backups' \+ --exclude='./scripts/test/output' \+ --exclude='*.png' \+ --exclude='*.jpeg' \+ --exclude='*.jpg' \+ --exclude='*.log' \+ --exclude='*.tmp' \+ --exclude='*.pyc' \+ . | tar -C "$BUILD_DIR" -xf -# ---------------------------------------------------------------------------# Build the frontend bundle@@ -82,6 +111,49 @@ cd "$BUILD_DIR/frontend"npm ci --prefer-offline 2>&1 | tail -5NODE_OPTIONS="--max-old-space-size=1024" npm run build 2>&1 | tail -10+# ---------------------------------------------------------------------------+# Build the Python virtual environment+# ---------------------------------------------------------------------------+step "Building Python virtual environment..."+VENV_BUILD_DIR="$BUILD_DIR/venv"+rm -rf "$VENV_BUILD_DIR"+# --copies embeds the Python interpreter so the venv does not depend on the+# target machine having the interpreter at the exact same system path.+python3 -m venv --copies "$VENV_BUILD_DIR"+# shellcheck source=/dev/null+source "$VENV_BUILD_DIR/bin/activate"+pip install --upgrade pip --quiet+pip install -r "$BUILD_DIR/backend/requirements.txt" --quiet+pip install gunicorn gevent gevent-websocket --quiet++# Make the venv relocatable: rewrite absolute paths in activate scripts and+# shebangs so the venv works at $TARGET_VENV_PATH on the target server.+make_venv_relocatable() {+ local venv_dir="$1"+ local current_path+ current_path="$(cd "$venv_dir" && pwd)"++ for f in "$venv_dir"/bin/activate*; do+ [ -f "$f" ] || continue+ sed -i "s|$current_path|$TARGET_VENV_PATH|g" "$f"+ done++ for f in "$venv_dir"/bin/*; do+ [ -f "$f" ] || continue+ if head -n1 "$f" | grep -q "^#!"; then+ sed -i "1s|$current_path|$TARGET_VENV_PATH|g" "$f"+ fi+ done++ # pyvenv.cfg command line is cosmetic, but keep it consistent.+ if [ -f "$venv_dir/pyvenv.cfg" ]; then+ sed -i "s|$current_path|$TARGET_VENV_PATH|g" "$venv_dir/pyvenv.cfg"+ fi+}++make_venv_relocatable "$VENV_BUILD_DIR"+good "Virtual environment built and relocated to $TARGET_VENV_PATH"+# ---------------------------------------------------------------------------# Strip development artifacts from the staged tree# ---------------------------------------------------------------------------@@ -96,24 +168,17 @@ find "$BUILD_DIR" -type f \( -name '*.png' -o -name '*.jpeg' -o -name '*.jpg' \)mkdir -p "$BUILD_DIR/backend/instance"# ----------------------------------------------------------------------------# Pack the tarball with an /opt/serverkit prefix+# Pack the tarball with an /opt/serverkit prefix and generate checksums# ---------------------------------------------------------------------------step "Creating the tarball..."-# Land the tarball at the repo root (matches .gitignore's /serverkit-*.tar.gz).DEST_DIR="$REPO_ROOT"-# Pack from the parent of BUILD_DIR with a transform so the archive contains-# /opt/serverkit without moving directories across filesystems.cd "$(dirname "$BUILD_DIR")"tar czf "${DEST_DIR}/${OUTPUT}" \--exclude='node_modules' \- --exclude='venv' \- --exclude='.venv' \- --exclude='.venv-wsl' \--exclude='__pycache__' \--exclude='.pytest_cache' \--exclude='instance' \- --exclude='dist' \--exclude='/backups' \--exclude='/backend/instance/backups' \--exclude='/backend/dev-data/backups' \@@ -130,10 +195,14 @@ tar czf "${DEST_DIR}/${OUTPUT}" \cd "$DEST_DIR"rm -rf "$BUILD_DIR"+sha256sum "$OUTPUT" > "$CHECKSUMS"+good "Release built: ${OUTPUT}"+good "Checksums: ${CHECKSUMS}"ls -lh "${OUTPUT}"+cat "$CHECKSUMS"printf '\n'-printf 'Upload this file to GitHub Releases: %s\n' "$OUTPUT"+printf 'Upload these files to GitHub Releases: %s and %s\n' "$OUTPUT" "$CHECKSUMS"printf 'Install with:\n'printf ' curl -fsSL https://serverkit.ai/install.sh | INSTALL_FROM_RELEASE=1 bash\n\n'diff --git a/scripts/update.sh b/scripts/update.shindex 170f5bf3..268d1873 100644--- a/scripts/update.sh+++ b/scripts/update.sh@@ -1,37 +1,96 @@#!/bin/bash#-# ServerKit updater.-#-# Pulls the newest code (or release tarball), rebuilds, and restarts the-# stack while preserving the database, generated secrets, and .env. A failed-# health check rolls the previous tree back into place.+# ServerKit updater — atomic blue/green, pre-flight checked, offline-capable.#+# Usage:# bash /opt/serverkit/scripts/update.sh-# INSTALL_FROM_RELEASE=1 bash /opt/serverkit/scripts/update.sh-# SERVERKIT_VERSION=v1.7.0 bash /opt/serverkit/scripts/update.sh+# bash /opt/serverkit/scripts/update.sh --dry-run+# bash /opt/serverkit/scripts/update.sh --branch dev+# bash /opt/serverkit/scripts/update.sh --release [v1.7.0]+# SERVERKIT_OFFLINE_TARBALL=/tmp/serverkit-v1.7.0-linux-amd64.tar.gz bash /opt/serverkit/scripts/update.sh#set -euo pipefail# ----------------------------------------------------------------------------# Automatic rollback on release swap failure+# Configuration + argument parsing+# ---------------------------------------------------------------------------+DRY_RUN=0+FORCE_UPDATE=0+TARGET_BRANCH=""+USE_RELEASE="${INSTALL_FROM_RELEASE:-0}"+RELEASE_VERSION="${SERVERKIT_VERSION:-}"++while [[ $# -gt 0 ]]; do+ case "$1" in+ --dry-run|-n)+ DRY_RUN=1+ shift+ ;;+ --force|-f)+ FORCE_UPDATE=1+ shift+ ;;+ --branch|-b)+ TARGET_BRANCH="$2"+ shift 2+ ;;+ --release|-r)+ USE_RELEASE=1+ if [[ -n "${2:-}" ]] && [[ ! "$2" =~ ^- ]]; then+ RELEASE_VERSION="$2"+ shift 2+ else+ shift+ fi+ ;;+ --help|-h)+ cat <<'EOF'+Usage: update.sh [OPTIONS]++Options:+ --dry-run, -n Show what would happen without making changes+ --force, -f Skip version comparison and update anyway+ --branch <name>, -b Update from a git branch instead of main+ --release [version], -r Update from a release tarball+ --help, -h Show this help message++Environment:+ SERVERKIT_DIR Active install directory (default: /opt/serverkit)+ SERVERKIT_VENV_DIR Python venv path (default: $SERVERKIT_DIR/venv)+ SERVERKIT_OFFLINE_TARBALL Local release tarball to use instead of downloading+ SERVERKIT_MIRROR_URL Base URL for release tarballs/checksums+ GITHUB_REPO GitHub org/repo for source and releases+EOF+ exit 0+ ;;+ *)+ echo "Unknown option: $1" >&2+ exit 1+ ;;+ esac+done+# ----------------------------------------------------------------------------cleanup_on_failure() {- local rc=$?- [ "$rc" -eq 0 ] && return 0- if [ ! -d "$INSTALL_DIR" ] && [ -d "$INSTALL_DIR.old" ]; then- warn "Update failed (exit $rc) — restoring previous installation..."- mv "$INSTALL_DIR.old" "$INSTALL_DIR"- systemctl daemon-reload 2>/dev/null || true- systemctl start "$BACKEND_SERVICE" 2>/dev/null || true- systemctl start nginx 2>/dev/null || true- warn "Rollback complete. Inspect logs: journalctl -u serverkit -n 50"- fi- return "$rc"-}-trap cleanup_on_failure EXIT+# Paths+# ---------------------------------------------------------------------------+SERVERKIT_DIR="${SERVERKIT_DIR:-/opt/serverkit}"+INSTALL_DIR="$SERVERKIT_DIR"+BASE_NAME="$(basename "$INSTALL_DIR")"+BASE_DIR="$(dirname "$INSTALL_DIR")"+DIR_A="$BASE_DIR/${BASE_NAME}-a"+DIR_B="$BASE_DIR/${BASE_NAME}-b"+VENV_DIR="${SERVERKIT_VENV_DIR:-$INSTALL_DIR/venv}"+BACKUP_DIR="/var/backups/serverkit"+LOG_DIR="/var/log/serverkit"+CONFIG_DIR="/etc/serverkit"++GITHUB_REPO="${GITHUB_REPO:-jhd3197/ServerKit}"+SERVERKIT_OFFLINE_TARBALL="${SERVERKIT_OFFLINE_TARBALL:-}"+SERVERKIT_MIRROR_URL="${SERVERKIT_MIRROR_URL:-}"+BACKEND_SERVICE="serverkit"# ----------------------------------------------------------------------------# Terminal styling (violet ServerKit identity, degrades to plain text)+# Terminal styling# ---------------------------------------------------------------------------if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != "dumb" ]; thenESC=$'\033'@@ -51,6 +110,7 @@ good() { printf ' %s✔%s %s\n' "$HUE_OK" "$RST" "$1"; }warn() { printf ' %s▴%s %s\n' "$HUE_WARN" "$RST" "$1"; }halt() { printf ' %s✘%s %s\n' "$HUE_ERR" "$RST" "$1" >&2; exit 1; }step() { printf ' %s❯%s %s\n' "$HUE_LINK" "$RST" "$1"; }+info() { printf ' %s•%s %s\n' "$FOG" "$RST" "$1"; }STARTED_AT=0PHASE_N=0@@ -67,97 +127,137 @@ phase() {}# ----------------------------------------------------------------------------# Settings+# Utility helpers# ----------------------------------------------------------------------------INSTALL_DIR="/opt/serverkit"-VENV_DIR="$INSTALL_DIR/venv"-BACKUP_DIR="/var/backups/serverkit"-GITHUB_REPO="${GITHUB_REPO:-jhd3197/ServerKit}"-INSTALL_FROM_RELEASE="${INSTALL_FROM_RELEASE:-0}"-BUILD_FROM_SOURCE="${BUILD_FROM_SOURCE:-0}"-SERVERKIT_VERSION="${SERVERKIT_VERSION:-}"-BACKEND_SERVICE="serverkit"+run_or_dry() {+ if [ "$DRY_RUN" = "1" ]; then+ info "[dry-run] would run: $*"+ else+ "$@"+ fi+}-# ----------------------------------------------------------------------------# Sanity checks-# ----------------------------------------------------------------------------[ "$EUID" -eq 0 ] || halt "Run as root."-[ -d "$INSTALL_DIR" ] || halt "ServerKit is not installed at $INSTALL_DIR"+wait_for_service() {+ local unit="$1" target_state="$2" timeout="${3:-30}"+ local waited=0+ while [ "$waited" -lt "$timeout" ]; do+ if systemctl is-active --quiet "$unit" 2>/dev/null; then+ [ "$target_state" = "active" ] && return 0+ else+ [ "$target_state" = "inactive" ] && return 0+ fi+ sleep 1+ waited=$((waited + 1))+ done+ return 1+}++# Resolve the currently active real directory behind the symlink.+active_real_dir() {+ if [ -L "$INSTALL_DIR" ]; then+ readlink -f "$INSTALL_DIR"+ elif [ -d "$INSTALL_DIR" ]; then+ echo "$INSTALL_DIR"+ else+ echo ""+ fi+}++# Return the inactive blue/green directory.+next_real_dir() {+ local active+ active="$(active_real_dir)"+ if [ "$active" = "$DIR_A" ]; then+ echo "$DIR_B"+ else+ echo "$DIR_A"+ fi+}# ----------------------------------------------------------------------------# Pick install mode: release tarball vs. source tree+# Pre-flight checks# ----------------------------------------------------------------------------# Default workflow: dev branch -> PR to main -> `serverkit update` on server.-# So unless the operator explicitly asks for a release tarball, we always pull-# the latest main source and rebuild. If the install came from a release-# tarball (no .git), we convert it to a shallow git checkout so future updates-# track main directly.-[ "$BUILD_FROM_SOURCE" = "1" ] && INSTALL_FROM_RELEASE=0+preflight_check() {+ phase "Pre-flight Checks"-if [ "$INSTALL_FROM_RELEASE" != "1" ] && [ ! -d "$INSTALL_DIR/.git" ]; then- step "No source tree found — converting install to a git checkout from main..."- tmp_env=$(mktemp)- tmp_db=$(mktemp)- cp "$INSTALL_DIR/.env" "$tmp_env" 2>/dev/null || true- cp "$INSTALL_DIR/backend/instance/serverkit.db" "$tmp_db" 2>/dev/null || true- rm -rf "$INSTALL_DIR"- git clone --depth 1 --branch main "https://github.com/${GITHUB_REPO}.git" "$INSTALL_DIR" \- || halt "Failed to clone ${GITHUB_REPO}.git"- cp "$tmp_env" "$INSTALL_DIR/.env" 2>/dev/null || true- mkdir -p "$INSTALL_DIR/backend/instance"- cp "$tmp_db" "$INSTALL_DIR/backend/instance/serverkit.db" 2>/dev/null || true- rm -f "$tmp_env" "$tmp_db"- step "Source tree cloned from main."-fi+ # Root+ if [ "$EUID" -ne 0 ]; then+ halt "Run as root."+ fi+ good "Running as root"-# ----------------------------------------------------------------------------# Self-refresh: replace this script with the release copy and re-exec, so an-# old updater can't drive a new release. Runs once (guarded by SELF_REFRESHED)-# and only in release mode. Kept inline so $@ / BASH_SOURCE resolve correctly.-# ----------------------------------------------------------------------------if [ "${SELF_REFRESHED:-0}" != "1" ] && [ "$INSTALL_FROM_RELEASE" = "1" ] \- && [ "${SERVERKIT_NO_SELF_REFRESH:-0}" != "1" ]; then- newest_tag=$(curl -fsSL "https://api.github.com/repos/${GITHUB_REPO}/releases/latest" 2>/dev/null \- | grep -m1 '"tag_name"' | cut -d'"' -f4 || true)- if [ -n "$newest_tag" ]; then- upstream="https://raw.githubusercontent.com/${GITHUB_REPO}/${newest_tag}/scripts/update.sh"- tmp=$(mktemp)- if curl -fsSL "$upstream" -o "$tmp" 2>/dev/null && [ -s "$tmp" ]; then- if ! cmp -s "$tmp" "${BASH_SOURCE[0]}"; then- step "Refreshing update.sh from $newest_tag..."- cp "$tmp" "${BASH_SOURCE[0]}" 2>/dev/null || true- rm -f "$tmp"- export SELF_REFRESHED=1- exec bash "${BASH_SOURCE[0]}" "$@"- fi+ # Install directory exists or can be created+ if [ ! -e "$BASE_DIR" ]; then+ halt "Base directory $BASE_DIR does not exist."+ fi+ good "Install base directory exists"++ # Python version+ local py_bin py_version+ py_bin="$(locate_python 2>/dev/null || true)"+ if [ -z "$py_bin" ]; then+ halt "Python 3.11 or 3.12 is required. Install python3.11/3.12 and python3-venv."+ fi+ py_version="$($py_bin -c 'import sys; print(".".join(map(str, sys.version_info[:2])))')"+ good "Python $py_version available ($py_bin)"++ # Required commands+ local cmd missing=()+ for cmd in git curl tar rsync systemctl nginx docker python3; do+ command -v "$cmd" &>/dev/null || missing+=("$cmd")+ done+ if ! docker compose version &>/dev/null && ! docker-compose --version &>/dev/null; then+ missing+=("docker compose")+ fi+ if [ ${#missing[@]} -gt 0 ]; then+ halt "Missing required tools: ${missing[*]}"+ fi+ good "Required tools available"++ # Disk space (need 2 GiB free on the install filesystem)+ local avail_kb avail_gb+ avail_kb="$(df -k "$BASE_DIR" | awk 'NR==2 {print $4}')"+ avail_gb=$((avail_kb / 1024 / 1024))+ if [ "$avail_gb" -lt 2 ]; then+ halt "Insufficient disk space on $BASE_DIR: ${avail_gb} GiB free (need at least 2 GiB)."+ fi+ good "Disk space OK (${avail_gb} GiB free)"++ # Memory (need 512 MiB free)+ local mem_avail_mb+ mem_avail_mb="$(awk '/MemAvailable:/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || echo 0)"+ if [ "$mem_avail_mb" -lt 512 ]; then+ warn "Low memory: ${mem_avail_mb} MiB available (recommend >= 512 MiB)."+ else+ good "Memory OK (${mem_avail_mb} MiB available)"+ fi++ # Network reachability (skip in offline mode)+ if [ -n "$SERVERKIT_OFFLINE_TARBALL" ]; then+ info "Offline tarball set; skipping network checks"+ elif [ "$USE_RELEASE" = "1" ] || [ -z "$TARGET_BRANCH" ]; then+ if ! curl -sfI "https://github.com" >/dev/null 2>&1; then+ halt "Cannot reach github.com. Set SERVERKIT_OFFLINE_TARBALL or fix network."fi- rm -f "$tmp"+ good "Network reachability OK"fi-fi-# ----------------------------------------------------------------------------# Backfill the encryption key for installs that pre-date secrets-at-rest-# ----------------------------------------------------------------------------backfill_encryption_key() {- local env_file="$INSTALL_DIR/.env"- if [ -f "$env_file" ] && ! grep -q '^SERVERKIT_ENCRYPTION_KEY=' "$env_file"; then- step "Generating SERVERKIT_ENCRYPTION_KEY..."- local key- key=$(python3 -c 'import base64, os; print(base64.urlsafe_b64encode(os.urandom(32)).decode())')- echo "SERVERKIT_ENCRYPTION_KEY=$key" >> "$env_file"- good "Encryption key added to $env_file"+ # Current backend health (warn only; it may already be down)+ if curl -sf --max-time 5 http://127.0.0.1:5000/api/v1/system/health >/dev/null 2>&1; then+ good "Backend currently healthy"+ else+ warn "Backend is not currently responding on :5000 — will proceed anyway"fi}-backfill_encryption_key# ----------------------------------------------------------------------------# Python virtual environment (release tarballs no longer ship a venv)+# Python virtual environment# ---------------------------------------------------------------------------locate_python() {local c vfor c in python3.12 python3.11 python3; doif command -v "$c" &>/dev/null; then- v=$("$c" -c 'import sys;print(".".join(map(str,sys.version_info[:2])))' 2>/dev/null || true)+ v="$($c -c 'import sys;print(".".join(map(str,sys.version_info[:2])))' 2>/dev/null || true)"if printf '%s\n%s' "3.11" "$v" | sort -C -V && \printf '%s\n%s' "$v" "3.12" | sort -C -V; thenprintf '%s' "$c"@@ -169,345 +269,516 @@ locate_python() {}rebuild_virtualenv() {- phase "Python Environment"+ local target_dir="$1"+ step "Rebuilding Python virtual environment..."local py_bin- py_bin=$(locate_python) || halt "ServerKit requires Python 3.11 or 3.12."- good "Using $py_bin"+ py_bin="$(locate_python)" || halt "ServerKit requires Python 3.11 or 3.12."- step "Recreating the virtual environment locally..."- rm -rf "$VENV_DIR"- "$py_bin" -m venv "$VENV_DIR"- # shellcheck source=/dev/null- source "$VENV_DIR/bin/activate"+ if [ "$DRY_RUN" = "1" ]; then+ info "[dry-run] would recreate venv at $target_dir using $py_bin"+ return 0+ fi- step "Installing Python dependencies..."+ rm -rf "$target_dir"+ "$py_bin" -m venv "$target_dir"+ # shellcheck source=/dev/null+ source "$target_dir/bin/activate"pip install --upgrade pip --quiet- pip install -r "$INSTALL_DIR/backend/requirements.txt" --quiet+ pip install -r "$target_dir/../backend/requirements.txt" --quietpip install gunicorn gevent gevent-websocket --quiet+ good "Virtual environment rebuilt at $target_dir"+}- good "Python environment rebuilt."+# Ensure the target directory has a usable venv. If a pre-built one exists, use+# it; otherwise rebuild from requirements.+require_venv() {+ local target_dir="$1"+ if [ -f "$target_dir/bin/activate" ] && [ -x "$target_dir/bin/python" ]; then+ good "Virtual environment ready at $target_dir"+ return 0+ fi+ warn "Virtual environment missing at $target_dir"+ rebuild_virtualenv "$target_dir"}# ----------------------------------------------------------------------------# Header+# Database migration# ----------------------------------------------------------------------------printf '\n %s%sServerKit Updater%s\n' "$BLD" "$PAPER" "$RST"-STARTED_AT=$(date +%s)+migrate_database() {+ local work_dir="$1"+ local venv="$work_dir/venv"-CURRENT_VERSION=$(cat "$INSTALL_DIR/VERSION" 2>/dev/null | tr -d '\n\r ' || echo "unknown")-step "Current version: $CURRENT_VERSION"+ step "Running database migrations..."+ if [ "$DRY_RUN" = "1" ]; then+ info "[dry-run] would run flask db upgrade in $work_dir/backend"+ return 0+ fi++ # shellcheck source=/dev/null+ source "$venv/bin/activate"+ cd "$work_dir/backend"++ if ! FLASK_ENV=production flask db upgrade; then+ halt "Database migration failed. The previous installation is still active."+ fi+ good "Database migrated"+}# ----------------------------------------------------------------------------# Pull latest source (source-mode only)+# Release download + checksum verification# ----------------------------------------------------------------------------if [ "$INSTALL_FROM_RELEASE" != "1" ] && [ -d "$INSTALL_DIR/.git" ]; then- phase "Syncing Repository"- cd "$INSTALL_DIR"- git stash -q 2>/dev/null || true- if git fetch --depth=1 origin main 2>/dev/null; then- git reset --hard FETCH_HEAD 2>&1 | tail -1- good "Repository synced to origin/main"+download_release() {+ local version="$1"+ local arch output tmp_dir base_url checksum_file tarball_url++ case "$(uname -m)" in+ x86_64|amd64) arch="amd64" ;;+ aarch64|arm64) arch="arm64" ;;+ *) halt "Unsupported architecture: $(uname -m)" ;;+ esac++ if [ -n "$SERVERKIT_OFFLINE_TARBALL" ]; then+ [ -f "$SERVERKIT_OFFLINE_TARBALL" ] || halt "Offline tarball not found: $SERVERKIT_OFFLINE_TARBALL"+ echo "$SERVERKIT_OFFLINE_TARBALL"+ return 0+ fi++ if [ -n "$SERVERKIT_MIRROR_URL" ]; then+ base_url="$SERVERKIT_MIRROR_URL"else- warn "Repo sync failed — keeping the existing source."+ base_url="https://github.com/${GITHUB_REPO}/releases/download/${version}"fi-fi++ tarball_url="${base_url}/serverkit-${version}-linux-${arch}.tar.gz"+ checksum_url="${base_url}/checksums.txt"+ tmp_dir="$(mktemp -d)"+ output="$tmp_dir/serverkit-${version}-linux-${arch}.tar.gz"++ step "Downloading release tarball (${arch})..."+ curl -sfL "$tarball_url" -o "$output" || halt "Failed to download $tarball_url"++ step "Verifying checksum..."+ if curl -sfL "$checksum_url" -o "$tmp_dir/checksums.txt"; then+ cd "$tmp_dir"+ if ! sha256sum -c <(grep "serverkit-${version}-linux-${arch}.tar.gz" checksums.txt) >/dev/null 2>&1; then+ halt "Checksum verification failed for release tarball."+ fi+ good "Checksum verified"+ else+ warn "Could not download checksums.txt — skipping verification"+ fi++ echo "$output"+}++# ---------------------------------------------------------------------------+# Blue/green directory management+# ---------------------------------------------------------------------------+ensure_bluegreen_layout() {+ # Convert legacy single-directory installs into the blue/green symlink layout.+ if [ -d "$INSTALL_DIR" ] && [ ! -L "$INSTALL_DIR" ]; then+ step "Migrating to blue/green layout..."+ if [ "$DRY_RUN" = "1" ]; then+ info "[dry-run] would move $INSTALL_DIR → $DIR_A and symlink $INSTALL_DIR → $DIR_A"+ return 0+ fi+ mv "$INSTALL_DIR" "$DIR_A"+ ln -s "$DIR_A" "$INSTALL_DIR"+ good "Migrated to blue/green layout"+ fi++ # Ensure both slots exist.+ if [ "$DRY_RUN" = "0" ]; then+ mkdir -p "$DIR_A" "$DIR_B"+ fi+}++atomic_switch() {+ local target="$1"+ if [ "$DRY_RUN" = "1" ]; then+ info "[dry-run] would switch symlink $INSTALL_DIR → $target"+ return 0+ fi+ ln -sfn "$target" "${INSTALL_DIR}.tmp"+ mv -Tf "${INSTALL_DIR}.tmp" "$INSTALL_DIR"+ good "Switched active install to $target"+}# ----------------------------------------------------------------------------# Back up database + install tree+# Backup# ----------------------------------------------------------------------------phase "Database Backup"-mkdir -p "$BACKUP_DIR"+backup_current() {+ phase "Database Backup"+ mkdir -p "$BACKUP_DIR"++ local active db_file backup_file+ active="$(active_real_dir)"+ db_file="$active/backend/instance/serverkit.db"-DB_FILE="$INSTALL_DIR/backend/instance/serverkit.db"-if [ -f "$DB_FILE" ]; then- BACKUP_FILE="$BACKUP_DIR/serverkit-pre-upgrade-$(date +%Y%m%d-%H%M%S).db"- if cp "$DB_FILE" "$BACKUP_FILE"; then- good "Database backed up to $BACKUP_FILE"+ if [ -f "$db_file" ]; then+ backup_file="$BACKUP_DIR/serverkit-pre-upgrade-$(date +%Y%m%d-%H%M%S).db"+ run_or_dry cp "$db_file" "$backup_file"+ good "Database backed up to $backup_file"else- halt "Database backup failed — aborting upgrade."+ warn "No SQLite database at $db_file — skipping DB backup"fi-else- warn "No SQLite database at $DB_FILE — skipping DB backup."-fi-BACKUP_TREE="$BACKUP_DIR/serverkit-tree-$(date +%Y%m%d-%H%M%S)"-mkdir -p "$BACKUP_TREE"-rsync -a --exclude=venv --exclude=backups --exclude=node_modules \- "$INSTALL_DIR/" "$BACKUP_TREE/" 2>/dev/null || \- cp -a "$INSTALL_DIR" "$BACKUP_TREE" 2>/dev/null || true-good "Install tree backed up."+ local tree_backup+ tree_backup="$BACKUP_DIR/serverkit-tree-$(date +%Y%m%d-%H%M%S)"+ if [ -d "$active" ]; then+ run_or_dry rsync -a --exclude=venv --exclude=backups --exclude=node_modules \+ "$active/" "$tree_backup/" 2>/dev/null || \+ run_or_dry cp -a "$active" "$tree_backup" 2>/dev/null || true+ good "Install tree backed up to $tree_backup"+ fi+}# ----------------------------------------------------------------------------# Stop the stack+# Deploy source into the next directory# ----------------------------------------------------------------------------phase "Stopping Services"-systemctl stop "$BACKEND_SERVICE" 2>/dev/null || true-systemctl stop nginx 2>/dev/null || true+deploy_source() {+ local target="$1"+ local branch="${2:-main}"++ phase "Updating Source"++ if [ "$DRY_RUN" = "1" ]; then+ info "[dry-run] would clone/pull $GITHUB_REPO:$branch into $target"+ return 0+ fi++ # Preserve .env and database across rewrites.+ local tmp_env tmp_db+ tmp_env="$(mktemp)"+ tmp_db="$(mktemp)"+ cp "$INSTALL_DIR/.env" "$tmp_env" 2>/dev/null || true+ cp "$INSTALL_DIR/backend/instance/serverkit.db" "$tmp_db" 2>/dev/null || true++ rm -rf "$target"+ git clone --depth 1 --branch "$branch" "https://github.com/${GITHUB_REPO}.git" "$target" \+ || halt "Failed to clone ${GITHUB_REPO}:$branch"++ cp "$tmp_env" "$target/.env" 2>/dev/null || true+ mkdir -p "$target/backend/instance"+ cp "$tmp_db" "$target/backend/instance/serverkit.db" 2>/dev/null || true+ rm -f "$tmp_env" "$tmp_db"++ chmod +x "$target/serverkit"+ chmod +x "$target/scripts/"*.sh 2>/dev/null || true++ good "Source updated to $branch in $target"+}# ----------------------------------------------------------------------------# Deploy: download a release, or rebuild from source+# Deploy release tarball into the next directory# ----------------------------------------------------------------------------if [ "$INSTALL_FROM_RELEASE" = "1" ]; then+deploy_release() {+ local target="$1"+ local version="$2"+phase "Downloading Release"- case "$(uname -m)" in- x86_64) DL_ARCH="amd64" ;;- aarch64|arm64) DL_ARCH="arm64" ;;- *) halt "Unsupported architecture: $(uname -m)" ;;- esac+ local tarball stage unpacked+ tarball="$(download_release "$version")"- if [ -n "$SERVERKIT_VERSION" ]; then- RELEASE_TAG="$SERVERKIT_VERSION"- step "Pinned release: $RELEASE_TAG"- else- step "Looking up the latest release..."- RELEASE_TAG=$(curl -sf "https://api.github.com/repos/${GITHUB_REPO}/releases/latest" \- | grep '"tag_name"' | head -1 | cut -d'"' -f4)- [ -n "$RELEASE_TAG" ] || halt "Could not determine the latest release."- good "Latest release: $RELEASE_TAG"- fi-- BASE_URL="https://github.com/${GITHUB_REPO}/releases/download/${RELEASE_TAG}"- TARBALL="/tmp/serverkit-${RELEASE_TAG}-linux-${DL_ARCH}.tar.gz"-- step "Downloading release tarball (${DL_ARCH})..."- curl -sfL "${BASE_URL}/serverkit-${RELEASE_TAG}-linux-${DL_ARCH}.tar.gz" -o "$TARBALL" \- || halt "Failed to download the release tarball."-- step "Unpacking release..."- STAGE="/tmp/serverkit-release-$$"- rm -rf "$STAGE"- mkdir -p "$STAGE"- tar xzf "$TARBALL" -C "$STAGE"- rm -f "$TARBALL"-- # Locate the unpacked tree. Older tarballs have a top-level `serverkit/`- # directory; newer ones use `opt/serverkit/` (matches the archive prefix).- UNPACKED_DIR="$STAGE/serverkit"- if [ ! -d "$UNPACKED_DIR" ]; then- UNPACKED_DIR="$STAGE/opt/serverkit"- fi- if [ ! -d "$UNPACKED_DIR" ]; then- UNPACKED_DIR=$(find "$STAGE" -maxdepth 2 -type d -name serverkit | head -n1)- fi- [ -d "$UNPACKED_DIR" ] || halt "Release tarball layout is unrecognized (expected serverkit/ or opt/serverkit/)."-- # Ensure the instance directory exists before copying the live database.- mkdir -p "$UNPACKED_DIR/backend/instance"-- # Carry the live .env and database across.- cp "$INSTALL_DIR/.env" "$UNPACKED_DIR/.env" 2>/dev/null || true- cp "$INSTALL_DIR/backend/instance/serverkit.db" \- "$UNPACKED_DIR/backend/instance/serverkit.db" 2>/dev/null || true-- # Remove any stale backup from a previous failed/interrupted update so- # mv doesn't try to overwrite a file/non-directory with a directory.- if [ -e "$INSTALL_DIR.old" ]; then- rm -rf "$INSTALL_DIR.old"- fi-- mv "$INSTALL_DIR" "$INSTALL_DIR.old"- mv "$UNPACKED_DIR" "$INSTALL_DIR"- rm -rf "$STAGE"-- # Release tarballs don't always preserve executable bits.- chmod +x "$INSTALL_DIR/serverkit"- chmod +x "$INSTALL_DIR/scripts/"*.sh 2>/dev/null || true- good "Release deployed."-- # Release tarballs no longer include a pre-built venv (the absolute paths- # break on the target). Rebuild it locally from requirements.txt.- rebuild_virtualenv-- # Release tarballs also don't ship pre-built frontend assets, and the- # docker-compose volume mount requires the dist/ tree on the host.- step "Rebuilding the frontend..."- cd "$INSTALL_DIR/frontend"- npm ci --prefer-offline 2>&1 | tail -3- NODE_OPTIONS="--max-old-space-size=1024" npm run build 2>&1 | tail -5- good "Frontend built."-else- phase "Updating Source"- cd "$INSTALL_DIR"+ if [ "$DRY_RUN" = "1" ]; then+ info "[dry-run] would unpack $tarball into $target"+ return 0+ fi- step "Pulling latest main from GitHub..."- git fetch origin- git reset --hard origin/main- good "Source updated to origin/main."+ stage="$(mktemp -d)"+ tar xzf "$tarball" -C "$stage"- chmod +x "$INSTALL_DIR/serverkit"- chmod +x "$INSTALL_DIR/scripts/"*.sh 2>/dev/null || true+ unpacked="$stage/serverkit"+ [ ! -d "$unpacked" ] && unpacked="$stage/opt/serverkit"+ if [ ! -d "$unpacked" ]; then+ unpacked="$(find "$stage" -maxdepth 2 -type d -name serverkit | head -n1)"+ fi+ [ -d "$unpacked" ] || halt "Release tarball layout is unrecognized"- step "Updating Python dependencies..."- source "$VENV_DIR/bin/activate"- pip install -r "$INSTALL_DIR/backend/requirements.txt" --quiet+ # Preserve live state.+ cp "$INSTALL_DIR/.env" "$unpacked/.env" 2>/dev/null || true+ mkdir -p "$unpacked/backend/instance"+ cp "$INSTALL_DIR/backend/instance/serverkit.db" "$unpacked/backend/instance/serverkit.db" 2>/dev/null || true- step "Syncing app templates..."- mkdir -p /etc/serverkit/templates- cp -r "$INSTALL_DIR/backend/templates/"*.yaml /etc/serverkit/templates/ 2>/dev/null || true- cp -r "$INSTALL_DIR/backend/templates/"*.yml /etc/serverkit/templates/ 2>/dev/null || true-- step "Rebuilding the frontend..."- cd "$INSTALL_DIR/frontend"- npm ci --prefer-offline 2>&1 | tail -3- NODE_OPTIONS="--max-old-space-size=1024" npm run build 2>&1 | tail -5-- step "Rebuilding the frontend container..."- cd "$INSTALL_DIR"- docker compose build 2>&1 | tail -5- good "Source updated."-fi+ rm -rf "$target"+ cp -a "$unpacked" "$target"+ rm -rf "$stage"++ chmod +x "$target/serverkit"+ chmod +x "$target/scripts/"*.sh 2>/dev/null || true++ good "Release $version deployed to $target"+}# ----------------------------------------------------------------------------# Refresh nginx + systemd from the new tree+# Configuration refresh# ----------------------------------------------------------------------------phase "Refreshing Configuration"+refresh_config() {+ local target="$1"-# Recover the panel domain baked into the *current* live config before we-# overwrite it -- older installs predate /etc/serverkit/panel-domain.-PRIOR_PANEL_DOMAIN=$(grep -oE '/etc/letsencrypt/live/[^/]+/' \- /etc/nginx/sites-available/serverkit.conf 2>/dev/null | head -n1 | \- sed -E 's|.*/live/([^/]+)/|\1|')-[ "$PRIOR_PANEL_DOMAIN" = "YOUR_DOMAIN" ] && PRIOR_PANEL_DOMAIN=""+ phase "Refreshing Configuration"-if [ -f "$INSTALL_DIR/nginx/sites-available/serverkit.conf" ]; then- cp "$INSTALL_DIR/nginx/sites-available/serverkit.conf" /etc/nginx/sites-available/-fi-if [ -f "$INSTALL_DIR/nginx/sites-available/serverkit-insecure.conf" ]; then- cp "$INSTALL_DIR/nginx/sites-available/serverkit-insecure.conf" /etc/nginx/sites-available/-fi+ if [ "$DRY_RUN" = "1" ]; then+ info "[dry-run] would refresh nginx + systemd configs from $target"+ return 0+ fi-# Re-apply the server-wide TLS floor (TLS 1.2/1.3 + AEAD ciphers) so existing-# installs get hardened on update too, not just fresh installs.-if [ -f /etc/nginx/nginx.conf ]; then- SK_CIPHERS='ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384'- if grep -qE '^[[:space:]]*ssl_protocols[[:space:]]' /etc/nginx/nginx.conf; then- sed -i -E 's|^([[:space:]]*)ssl_protocols[[:space:]].*|\1ssl_protocols TLSv1.2 TLSv1.3;|' /etc/nginx/nginx.conf- else- sed -i '/http {/a \ ssl_protocols TLSv1.2 TLSv1.3;' /etc/nginx/nginx.conf+ # Recover panel domain from live nginx config.+ local prior_panel_domain=""+ prior_panel_domain=$(grep -oE '/etc/letsencrypt/live/[^/]+/' \+ /etc/nginx/sites-available/serverkit.conf 2>/dev/null | head -n1 | \+ sed -E 's|.*/live/([^/]+)/|\1|')+ [ "$prior_panel_domain" = "YOUR_DOMAIN" ] && prior_panel_domain=""++ if [ -f "$target/nginx/sites-available/serverkit.conf" ]; then+ cp "$target/nginx/sites-available/serverkit.conf" /etc/nginx/sites-available/fi- if grep -qE '^[[:space:]]*ssl_ciphers[[:space:]]' /etc/nginx/nginx.conf; then- sed -i -E "s|^([[:space:]]*)ssl_ciphers[[:space:]].*|\1ssl_ciphers ${SK_CIPHERS};|" /etc/nginx/nginx.conf- else- sed -i "/http {/a \\ ssl_ciphers ${SK_CIPHERS};" /etc/nginx/nginx.conf+ if [ -f "$target/nginx/sites-available/serverkit-insecure.conf" ]; then+ cp "$target/nginx/sites-available/serverkit-insecure.conf" /etc/nginx/sites-available/fi-fi-# Preserve the user's secure/insecure SSL choice across updates.-SSL_MODE="insecure"-if [ -f /etc/serverkit/ssl-mode ]; then- SSL_MODE=$(cat /etc/serverkit/ssl-mode)-fi-if [ "$SSL_MODE" = "secure" ] && [ -f /etc/nginx/sites-available/serverkit.conf ]; then- # Recover the panel domain: prefer the value install.sh persisted, then the- # one scraped from the prior live config above. (The old .env scrape was- # broken -- SERVERKIT_PUBLIC_URL is written commented out.)- PANEL_DOMAIN="${PANEL_DOMAIN:-}"- if [ -z "$PANEL_DOMAIN" ] && [ -f /etc/serverkit/panel-domain ]; then- PANEL_DOMAIN=$(cat /etc/serverkit/panel-domain 2>/dev/null || true)- fi- [ -z "$PANEL_DOMAIN" ] && PANEL_DOMAIN="$PRIOR_PANEL_DOMAIN"-- if [ -n "$PANEL_DOMAIN" ] && [ -d "/etc/letsencrypt/live/$PANEL_DOMAIN" ]; then- sed -i "s|/etc/letsencrypt/live/YOUR_DOMAIN/|/etc/letsencrypt/live/$PANEL_DOMAIN/|g" \- /etc/nginx/sites-available/serverkit.conf- ln -sf /etc/nginx/sites-available/serverkit.conf /etc/nginx/sites-enabled/serverkit.conf+ # TLS floor+ if [ -f /etc/nginx/nginx.conf ]; then+ local ciphers='ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384'+ if grep -qE '^[[:space:]]*ssl_protocols[[:space:]]' /etc/nginx/nginx.conf; then+ sed -i -E 's|^([[:space:]]*)ssl_protocols[[:space:]].*|\1ssl_protocols TLSv1.2 TLSv1.3;|' /etc/nginx/nginx.conf+ else+ sed -i '/http {/a \ ssl_protocols TLSv1.2 TLSv1.3;' /etc/nginx/nginx.conf+ fi+ if grep -qE '^[[:space:]]*ssl_ciphers[[:space:]]' /etc/nginx/nginx.conf; then+ sed -i -E "s|^([[:space:]]*)ssl_ciphers[[:space:]].*|\1ssl_ciphers ${ciphers};|" /etc/nginx/nginx.conf+ else+ sed -i "/http {/a \\ ssl_ciphers ${ciphers};" /etc/nginx/nginx.conf+ fi+ fi++ # SSL mode+ local ssl_mode="insecure"+ if [ -f "$CONFIG_DIR/ssl-mode" ]; then+ ssl_mode="$(cat "$CONFIG_DIR/ssl-mode")"+ fi+ if [ "$ssl_mode" = "secure" ] && [ -f /etc/nginx/sites-available/serverkit.conf ]; then+ local panel_domain=""+ if [ -f "$CONFIG_DIR/panel-domain" ]; then+ panel_domain="$(cat "$CONFIG_DIR/panel-domain" 2>/dev/null || true)"+ fi+ [ -z "$panel_domain" ] && panel_domain="$prior_panel_domain"++ if [ -n "$panel_domain" ] && [ -d "/etc/letsencrypt/live/$panel_domain" ]; then+ sed -i "s|/etc/letsencrypt/live/YOUR_DOMAIN/|/etc/letsencrypt/live/$panel_domain/|g" \+ /etc/nginx/sites-available/serverkit.conf+ ln -sf /etc/nginx/sites-available/serverkit.conf /etc/nginx/sites-enabled/serverkit.conf+ else+ warn "SSL mode is 'secure' but no certificate found for '${panel_domain:-unknown}'"+ ln -sf /etc/nginx/sites-available/serverkit-insecure.conf /etc/nginx/sites-enabled/serverkit.conf+ fielse- warn "SSL mode is 'secure' but no certificate was found for '${PANEL_DOMAIN:-unknown}'."- warn "Using the HTTP config so nginx still reloads. Re-run certbot to restore HTTPS."ln -sf /etc/nginx/sites-available/serverkit-insecure.conf /etc/nginx/sites-enabled/serverkit.conffi-else- ln -sf /etc/nginx/sites-available/serverkit-insecure.conf /etc/nginx/sites-enabled/serverkit.conf-fi-mkdir -p /etc/nginx/serverkit-locations-for conf in /etc/nginx/sites-enabled/*; do- [ -f "$conf" ] || continue- name=$(basename "$conf")- case "$name" in serverkit-*) continue ;; esac- if grep -Eq 'server_name[[:space:]]+_;' "$conf" 2>/dev/null; then- warn "Removing conflicting catch-all config: $name"- rm -f "/etc/nginx/sites-enabled/$name" "/etc/nginx/sites-available/$name"+ # Service unit+ if [ -f "$target/serverkit-backend.service" ]; then+ cp "$target/serverkit-backend.service" /etc/systemd/system/serverkit.servicefi-done--if [ -f "$INSTALL_DIR/serverkit-backend.service" ]; then- cp "$INSTALL_DIR/serverkit-backend.service" /etc/systemd/system/serverkit.service-fi-systemctl daemon-reload-good "Configuration refreshed."+ systemctl daemon-reload+ good "Configuration refreshed"+}# ----------------------------------------------------------------------------# Bring the stack back up+# Rollback# ----------------------------------------------------------------------------phase "Starting Services"-systemctl start "$BACKEND_SERVICE"-cd "$INSTALL_DIR"-# Recreate the frontend container so its bind mount follows the current-# frontend/dist inode (npm run build deletes and recreates the directory).-docker compose up -d --force-recreate frontend 2>&1 | tail -5-docker compose up -d backend 2>&1 | tail -5-systemctl start nginx-good "Services started."+rollback() {+ warn "Update failed — rolling back to previous slot..."-# ----------------------------------------------------------------------------# Health check; restore the previous tree on failure-# ----------------------------------------------------------------------------phase "Health Check"+ if [ -z "${PREVIOUS_DIR:-}" ] || [ ! -d "$PREVIOUS_DIR" ]; then+ halt "Cannot roll back: previous installation directory not available"+ fi-roll_back() {- warn "Health check failed — rolling back..."systemctl stop "$BACKEND_SERVICE" 2>/dev/null || true+ wait_for_service "$BACKEND_SERVICE" inactive 30 || truesystemctl stop nginx 2>/dev/null || true- if [ -d "$INSTALL_DIR.old" ]; then- rm -rf "$INSTALL_DIR"- mv "$INSTALL_DIR.old" "$INSTALL_DIR"- warn "Restored the previous installation from $INSTALL_DIR.old"- fi+ wait_for_service nginx inactive 15 || true++ atomic_switch "$PREVIOUS_DIR"+systemctl daemon-reloadsystemctl start "$BACKEND_SERVICE" 2>/dev/null || true+ wait_for_service "$BACKEND_SERVICE" active 30 || true+ cd "$INSTALL_DIR" && docker compose up -d --force-recreate frontend 2>&1 | tail -5+ docker compose up -d backend 2>&1 | tail -5systemctl start nginx 2>/dev/null || true- halt "Update rolled back. Inspect logs: journalctl -u serverkit -n 50"+ wait_for_service nginx active 15 || true++ halt "Rolled back to $(active_real_dir). Inspect logs: journalctl -u serverkit -n 50"}-step "Waiting for the backend to answer..."-WAITED=0-while [ "$WAITED" -lt 30 ]; do- if curl -sf --max-time 5 http://127.0.0.1:5000/api/v1/system/health >/dev/null 2>&1; then- good "Backend healthy."- break+# ---------------------------------------------------------------------------+# Health check+# ---------------------------------------------------------------------------+health_check() {+ phase "Health Check"++ if [ "$DRY_RUN" = "1" ]; then+ info "[dry-run] would probe http://127.0.0.1:5000/api/v1/system/health"+ return 0fi- sleep 2- WAITED=$((WAITED + 2))-done-[ "$WAITED" -ge 30 ] && roll_back-# Second probe as a belt-and-suspenders gate before we discard the old tree.-curl -sf --max-time 5 http://127.0.0.1:5000/api/v1/system/health >/dev/null 2>&1 || roll_back+ step "Waiting for backend..."+ local waited=0+ while [ "$waited" -lt 60 ]; do+ if curl -sf --max-time 5 http://127.0.0.1:5000/api/v1/system/health >/dev/null 2>&1; then+ good "Backend healthy"+ break+ fi+ sleep 2+ waited=$((waited + 2))+ done+ if [ "$waited" -ge 60 ]; then+ rollback+ fi++ if ! curl -sf --max-time 5 http://127.0.0.1:5000/api/v1/system/health >/dev/null 2>&1; then+ rollback+ fi++ # Verify frontend container is running.+ if docker compose ps 2>/dev/null | grep -q "frontend.*Up"; then+ good "Frontend container running"+ else+ warn "Frontend container not reported as Up yet"+ fi++ HEALTH_PASSED=1+}# ----------------------------------------------------------------------------# Cleanup + telemetry+# Cleanup# ----------------------------------------------------------------------------phase "Cleanup"+cleanup() {+ phase "Cleanup"-[ -d "$INSTALL_DIR.old" ] && rm -rf "$INSTALL_DIR.old"+ if [ "$DRY_RUN" = "1" ]; then+ info "[dry-run] would trim old backups"+ return 0+ fi-# Keep only the 10 most recent backups of each kind.-ls -t "$BACKUP_DIR"/serverkit-tree-* 2>/dev/null | tail -n +11 | xargs -r rm -rf-ls -t "$BACKUP_DIR"/serverkit-pre-upgrade-*.db 2>/dev/null | tail -n +11 | xargs -r rm -f+ ls -t "$BACKUP_DIR"/serverkit-tree-* 2>/dev/null | tail -n +11 | xargs -r rm -rf+ ls -t "$BACKUP_DIR"/serverkit-pre-upgrade-*.db 2>/dev/null | tail -n +11 | xargs -r rm -f-NEW_VERSION=$(cat "$INSTALL_DIR/VERSION" 2>/dev/null | tr -d '\n\r ' || echo "unknown")-curl -s "https://serverkit.ai/track/update?v=${NEW_VERSION}" >/dev/null 2>&1 || true-good "Cleanup complete."+ local new_version+ new_version="$(cat "$INSTALL_DIR/VERSION" 2>/dev/null | tr -d '\n\r ' || echo "unknown")"+ curl -s "https://serverkit.ai/track/update?v=${new_version}" >/dev/null 2>&1 || true+ good "Cleanup complete"+}# ----------------------------------------------------------------------------# Summary+# Main# ---------------------------------------------------------------------------+printf '\n %s%sServerKit Updater%s\n' "$BLD" "$PAPER" "$RST"+STARTED_AT=$(date +%s)++[ "$DRY_RUN" = "1" ] && warn "DRY RUN — no changes will be made"++# If the update fails after we have switched the symlink, roll back to the+# previous slot automatically.+cleanup_on_exit() {+ local rc=$?+ [ "$rc" -eq 0 ] && return 0+ if [ "$DRY_RUN" = "0" ] && [ -n "${PREVIOUS_DIR:-}" ] && \+ [ "${ROLLING_BACK:-0}" != "1" ] && [ "${HEALTH_PASSED:-0}" != "1" ]; then+ ROLLING_BACK=1+ rollback+ fi+ return "$rc"+}+trap cleanup_on_exit EXIT++preflight_check+ensure_bluegreen_layout+backup_current++# Determine update mode.+NEXT_DIR="$(next_real_dir)"++if [ "$USE_RELEASE" = "1" ]; then+ if [ -z "$RELEASE_VERSION" ]; then+ RELEASE_VERSION="$(curl -sf "https://api.github.com/repos/${GITHUB_REPO}/releases/latest" \+ | grep '"tag_name"' | head -1 | cut -d'"' -f4)"+ [ -n "$RELEASE_VERSION" ] || halt "Could not determine the latest release"+ fi+ step "Updating to release $RELEASE_VERSION"+ deploy_release "$NEXT_DIR" "$RELEASE_VERSION"+elif [ -n "$TARGET_BRANCH" ]; then+ step "Updating to branch $TARGET_BRANCH"+ deploy_source "$NEXT_DIR" "$TARGET_BRANCH"+else+ deploy_source "$NEXT_DIR" "main"+fi++# Ensure venv in the new tree.+require_venv "$NEXT_DIR/venv"++# Run database migrations before switching.+migrate_database "$NEXT_DIR"++# Sync templates.+if [ "$DRY_RUN" = "0" ]; then+ mkdir -p /etc/serverkit/templates+ cp -r "$NEXT_DIR/backend/templates/"*.yaml /etc/serverkit/templates/ 2>/dev/null || true+ cp -r "$NEXT_DIR/backend/templates/"*.yml /etc/serverkit/templates/ 2>/dev/null || true+fi++# Build frontend if dist is missing (source mode or older release).+if [ ! -d "$NEXT_DIR/frontend/dist" ]; then+ step "Building frontend..."+ if [ "$DRY_RUN" = "0" ]; then+ cd "$NEXT_DIR/frontend"+ npm ci --prefer-offline 2>&1 | tail -3+ NODE_OPTIONS="--max-old-space-size=1024" npm run build 2>&1 | tail -5+ else+ info "[dry-run] would npm ci + npm run build in $NEXT_DIR/frontend"+ fi+fi++# Refresh nginx/systemd configs in the active tree before switch.+refresh_config "$NEXT_DIR"++# Stop services.+phase "Stopping Services"+run_or_dry systemctl stop "$BACKEND_SERVICE"+wait_for_service "$BACKEND_SERVICE" inactive 30 || warn "Backend did not stop within 30 seconds"+run_or_dry systemctl stop nginx+wait_for_service nginx inactive 15 || warn "nginx did not stop within 15 seconds"++# Record the currently active directory before switching.+PREVIOUS_DIR="$(active_real_dir)"++# Atomic switch.+atomic_switch "$NEXT_DIR"++# Start services.+phase "Starting Services"+run_or_dry systemctl start "$BACKEND_SERVICE"+wait_for_service "$BACKEND_SERVICE" active 30 || warn "Backend did not report active within 30 seconds"+run_or_dry cd "$INSTALL_DIR" && run_or_dry docker compose up -d --force-recreate frontend+run_or_dry docker compose up -d backend+run_or_dry systemctl start nginx+wait_for_service nginx active 15 || warn "nginx did not report active within 15 seconds"+good "Services started"++# Health check.+health_check++# Cleanup.+cleanup++# Summary.printf '\n %s%s✔ Update complete%s %s%s%s\n\n' \"$BLD" "$HUE_OK" "$RST" "$FOG" "$(clock)" "$RST"-printf ' Version %s\n' "$NEW_VERSION"-printf ' Backend %s\n' "$(systemctl is-active serverkit)"-printf ' Nginx %s\n\n' "$(systemctl is-active nginx)"+printf ' Version %s\n' "$(cat "$INSTALL_DIR/VERSION" 2>/dev/null | tr -d '\n\r ' || echo "unknown")"+printf ' Active %s\n' "$(active_real_dir)"+printf ' Backend %s\n' "$(systemctl is-active serverkit 2>/dev/null || echo unknown)"+printf ' Nginx %s\n\n' "$(systemctl is-active nginx 2>/dev/null || echo unknown)"printf ' %sCLI%s serverkit status\n\n' "$BLD" "$RST"diff --git a/serverkit b/serverkitindex d3e3fe4e..ac5949ad 100644--- a/serverkit+++ b/serverkit@@ -35,7 +35,7 @@ HUE_OK_TC="$(paint 52 211 153)"; HUE_WARN_TC="$(paint 250 204 21)"; HUE_ERR_TC="# ConfigurationINSTALL_DIR="${SERVERKIT_DIR:-/opt/serverkit}"-VENV_DIR="$INSTALL_DIR/venv"+VENV_DIR="${SERVERKIT_VENV_DIR:-$INSTALL_DIR/venv}"BACKEND_SERVICE="serverkit"FRONTEND_CONTAINER="serverkit-frontend"@@ -76,8 +76,32 @@ check_installed() {fi}+require_venv() {+ # If the expected virtual environment is missing, try to locate an existing+ # one from legacy/alternative layouts before giving up.+ if [ ! -f "$VENV_DIR/bin/activate" ] || [ ! -x "$VENV_DIR/bin/python" ]; then+ print_warning "Virtual environment missing at $VENV_DIR"+ local candidate found_venv=""+ for candidate in "$INSTALL_DIR/venv" "$INSTALL_DIR/backend/venv" \+ "$INSTALL_DIR/backend/.venv" "$INSTALL_DIR/.venv"; do+ if [ -f "$candidate/bin/activate" ] && [ -x "$candidate/bin/python" ]; then+ found_venv="$candidate"+ break+ fi+ done+ if [ -n "$found_venv" ] && [ "$found_venv" != "$VENV_DIR" ]; then+ print_info "Using virtual environment at $found_venv"+ VENV_DIR="$found_venv"+ else+ print_error "No usable Python virtual environment found. Run serverkit update to rebuild it."+ exit 1+ fi+ fi+}+run_cli() {# Run CLI commands directly on host using the virtual environment+ require_venvcd "$INSTALL_DIR/backend"source "$VENV_DIR/bin/activate"python cli.py "$@"@@ -180,7 +204,8 @@ cmd_help() {echo " update [options] Update ServerKit"echo " --branch <name> Switch to specific branch (e.g., dev)"echo " --release [vX.Y.Z] Update from release tarball"- echo " --force Skip version check"+ echo " --force Force update even if already latest"+ echo " --dry-run Show what would change without applying"echo " branch Show current branch"echo " uninstall Uninstall ServerKit"echo ""@@ -381,31 +406,32 @@ cmd_branch() {}cmd_update() {- local force_update=false- local target_branch=""- local use_release=false- local release_version=""+ local update_args=()- # Parse arguments+ # Parse arguments and forward them to the canonical update script.while [[ $# -gt 0 ]]; docase $1 in--force|-f)- force_update=true+ update_args+=("--force")shift;;--branch|-b)- target_branch="$2"+ update_args+=("--branch" "$2")shift 2;;--release|-r)- use_release=true+ update_args+=("--release")if [[ -n "${2:-}" ]] && [[ ! "$2" =~ ^- ]]; then- release_version="$2"+ update_args+=("$2")shift 2elseshiftfi;;+ --dry-run|-n)+ update_args+=("--dry-run")+ shift+ ;;*)shift;;@@ -417,184 +443,13 @@ cmd_update() {print_headerecho ""- # Dev mode: branch-based source update- if [ -n "$target_branch" ]; then- if [ ! -d "$INSTALL_DIR/.git" ]; then- print_error "Cannot switch branches: $INSTALL_DIR is not a git repository (release install)."- print_info "Use 'serverkit update --release' to update from a release tarball."- exit 1- fi- _update_source "$target_branch" "$force_update"- return- fi-- # Release mode: download pre-built tarball- if [ "$use_release" = true ]; then- if [ -n "$release_version" ]; then- SERVERKIT_VERSION="$release_version" bash "$INSTALL_DIR/scripts/update.sh"- else- INSTALL_FROM_RELEASE=1 bash "$INSTALL_DIR/scripts/update.sh"- fi- return- fi-- # Default mode: prefer robust update.sh if available- if [ -x "$INSTALL_DIR/scripts/update.sh" ]; then- bash "$INSTALL_DIR/scripts/update.sh"- return- fi-- # Fallback to legacy inline source update- _update_source "main" "$force_update"-}--_update_source() {- local target_branch="$1"- local force_update="$2"-- cd "$INSTALL_DIR"-- # Get current branch- local current_branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "main")-- # If no branch specified, use current branch (or main if detached)- if [ -z "$target_branch" ]; then- target_branch="$current_branch"- if [ "$target_branch" = "HEAD" ]; then- target_branch="main"- fi- fi-- # Get versions- CURRENT_VERSION=$(get_local_version)-- # For non-main branches, skip version comparison- if [ "$target_branch" != "main" ]; then- force_update=true- print_warning "Updating to branch: $target_branch (dev mode)"- echo ""- else- REMOTE_VERSION=$(get_remote_version)- echo " Installed version: $CURRENT_VERSION"- echo " Latest version: $REMOTE_VERSION"- echo ""- fi-- # Check if update is needed (skip if --force or non-main branch)- if [ "$force_update" = false ] && [ "$REMOTE_VERSION" != "unknown" ]; then- set +e # Temporarily disable exit on error- compare_versions "$CURRENT_VERSION" "$REMOTE_VERSION"- local result=$?- set -e # Re-enable exit on error- if [ $result -eq 0 ]; then- print_success "Already running the latest version."- echo ""- read -p "Force update anyway? [y/N] " -n 1 -r- echo ""- if [[ ! $REPLY =~ ^[Yy]$ ]]; then- exit 0- fi- fi- fi-- print_info "Updating ServerKit to branch: $target_branch..."-- # Stop services- print_info "Stopping services..."- systemctl stop $BACKEND_SERVICE || true- docker compose down || true-- # Fetch all branches and pull changes- print_info "Fetching latest changes..."- git fetch origin --prune-- # Checkout target branch- print_info "Switching to branch: $target_branch..."- git checkout "$target_branch" 2>/dev/null || git checkout -b "$target_branch" "origin/$target_branch"- git reset --hard "origin/$target_branch"-- # Restore executable permissions- chmod +x "$INSTALL_DIR/serverkit"- chmod +x "$INSTALL_DIR/scripts/"*.sh 2>/dev/null || true-- # Ensure SERVERKIT_ENCRYPTION_KEY exists for installs that pre-date it- if ! grep -q '^SERVERKIT_ENCRYPTION_KEY=' "$INSTALL_DIR/.env" 2>/dev/null; then- print_info "Generating SERVERKIT_ENCRYPTION_KEY for existing install..."- key=$(python3 -c 'import base64, os; print(base64.urlsafe_b64encode(os.urandom(32)).decode())')- echo "" >> "$INSTALL_DIR/.env"- echo "# Encryption key for agent pairing payloads and secrets at rest" >> "$INSTALL_DIR/.env"- echo "SERVERKIT_ENCRYPTION_KEY=$key" >> "$INSTALL_DIR/.env"- print_success "SERVERKIT_ENCRYPTION_KEY added to .env"- fi-- # Get new version from VERSION file- NEW_VERSION=$(get_local_version)- NEW_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")-- # Update Python dependencies- print_info "Updating Python dependencies..."- source "$VENV_DIR/bin/activate"- pip install -r "$INSTALL_DIR/backend/requirements.txt" --quiet-- # Sync app templates- print_info "Syncing app templates..."- mkdir -p /etc/serverkit/templates- cp -r "$INSTALL_DIR/backend/templates/"*.yaml /etc/serverkit/templates/ 2>/dev/null || true- cp -r "$INSTALL_DIR/backend/templates/"*.yml /etc/serverkit/templates/ 2>/dev/null || true-- # Remove any nginx configs that use server_name _ besides serverkit-managed ones- mkdir -p /etc/nginx/serverkit-locations- for conf in /etc/nginx/sites-enabled/*; do- [ -f "$conf" ] || continue- name=$(basename "$conf")- # Skip all ServerKit-managed configs- case "$name" in serverkit-*) continue ;; esac- if grep -Eq 'server_name[[:space:]]+_;' "$conf" 2>/dev/null; then- print_warning "Removing conflicting catch-all config: $name"- rm -f "/etc/nginx/sites-enabled/$name"- rm -f "/etc/nginx/sites-available/$name"- fi- done-- # Update main nginx config- if [ -f "$INSTALL_DIR/nginx/sites-available/serverkit.conf" ]; then- cp "$INSTALL_DIR/nginx/sites-available/serverkit.conf" /etc/nginx/sites-available/- fi-- # Clean up Docker to prevent networking issues- print_info "Cleaning up Docker..."- docker network prune -f 2>/dev/null || true- docker system prune -f 2>/dev/null || true-- # Rebuild frontend (no cache to ensure fresh build)- print_info "Rebuilding frontend..."- docker compose build --no-cache-- # Reload systemd in case service file changed- systemctl daemon-reload-- # Restart services- print_info "Starting services..."- systemctl start $BACKEND_SERVICE- docker compose up -d-- sleep 5-- # Track successful update- curl -s "https://serverkit.ai/track/update?v=${NEW_VERSION}" >/dev/null 2>&1 || true-- echo ""- print_success "ServerKit updated!"- echo " Branch: $target_branch"- echo " Commit: $NEW_COMMIT"- echo " Version: $NEW_VERSION"- echo ""-- if [ "$target_branch" != "main" ]; then- print_warning "Running on '$target_branch' branch. Use 'serverkit update --branch main' to return to stable."+ if [ ! -x "$INSTALL_DIR/scripts/update.sh" ]; then+ print_error "Updater not found at $INSTALL_DIR/scripts/update.sh"+ exit 1fi- cmd_status_brief+ SERVERKIT_DIR="$INSTALL_DIR" SERVERKIT_VENV_DIR="$VENV_DIR" \+ bash "$INSTALL_DIR/scripts/update.sh" "${update_args[@]}"}cmd_uninstall() {@@ -633,7 +488,12 @@ cmd_uninstall() {print_info "Removing files..."rm -f /etc/systemd/system/serverkit.servicerm -f /usr/local/bin/serverkit++ # Remove the active symlink plus both blue/green slots and backups.rm -rf "$INSTALL_DIR"+ rm -rf "${INSTALL_DIR}-a"+ rm -rf "${INSTALL_DIR}-b"+ rm -rf "${INSTALL_DIR}.backup"rm -rf /var/log/serverkitrm -rf /var/lib/serverkit