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): guided install/update flow with health-checked rollback
Juan Denisf9c31aec32f7
diff --git a/.gitignore b/.gitignoreindex f6f1618e..f08971e7 100644--- a/.gitignore+++ b/.gitignore@@ -106,6 +106,7 @@ nulSECURITY_AUDIT.mdAPP_IMPROVEMENTS.mdUI_REPORT.md+SECURITY_AND_CODE_AUDIT.md# Scratch screenshots dropped at the repo root. Real image assets live under# frontend/ or are force-included below (agent/internal/setupui/*).*.png@@ -116,6 +117,11 @@ UI_REPORT.md/agent/packaging/msi/output//agent/packaging/msi/*.wixpdb+# Release tarballs built by scripts/build-release.sh+/serverkit-*.tar.gz+/serverkit-*.tar.gz.sha256+/serverkit.bak+# Brand assets that the agent embeds at build time are generated by# agent/packaging/icons/generate_icons.py from the SVG, but must be checked# in so CI builds don't have to install cairo/Pillow.diff --git a/install.sh b/install.shindex 85595c6e..08c0fa18 100644--- a/install.sh+++ b/install.sh@@ -1,390 +1,537 @@#!/bin/bash#-# ServerKit Quick Install Script for Ubuntu/Debian/Fedora+# ServerKit bootstrap installer.#-# Architecture:-# - Backend: Runs directly on host (for full system access)-# - Frontend: Runs in Docker (nginx serving static files)+# curl -fsSL https://serverkit.ai/install.sh | bash#-# Usage: curl -fsSL https://serverkit.ai/install.sh | bash+# By default the script clones the repository and builds from source. Two+# environment switches change that:#+# INSTALL_FROM_RELEASE=1 fetch a pre-built tarball instead of compiling+# BUILD_FROM_SOURCE=1 force a source build even when a release exists+#+# The Flask backend runs straight on the host (it needs real system access);+# the React frontend is built to static files and served by the host nginx.+#+set -euo pipefail-set -e--# Safety: Move to a valid directory first-# Prevents "getcwd: cannot access parent directories" error-# when running from a deleted directory (e.g., after uninstall)-cd /tmp 2>/dev/null || cd / || true--# Colors-RED='\033[0;31m'-GREEN='\033[0;32m'-YELLOW='\033[1;33m'-BLUE='\033[0;34m'-NC='\033[0m'-+# ---------------------------------------------------------------------------+# Settings and environment contract+# ---------------------------------------------------------------------------INSTALL_DIR="/opt/serverkit"VENV_DIR="$INSTALL_DIR/venv"LOG_DIR="/var/log/serverkit"DATA_DIR="/var/lib/serverkit"+BACKUP_DIR="/var/backups/serverkit"+CONFIG_DIR="/etc/serverkit"-# Python constraintsPYTHON_MIN="3.11"PYTHON_MAX="3.12"PYTHON_BIN=""+GITHUB_REPO="${GITHUB_REPO:-jhd3197/ServerKit}"+INSTALL_FROM_RELEASE="${INSTALL_FROM_RELEASE:-0}"+BUILD_FROM_SOURCE="${BUILD_FROM_SOURCE:-0}"+SERVERKIT_VERSION="${SERVERKIT_VERSION:-}"+VERSION="${VERSION:-${SERVERKIT_VERSION:-1.4.11}}"+CHANNEL="${CHANNEL:-Stable}"++PANEL_DOMAIN="${PANEL_DOMAIN:-}"+PANEL_PORT="${PANEL_PORT:-80}"++# Runtime state populated as we go (declared up-front for `set -u`).+OS_FAMILY="unknown"+ARCH=""+DL_ARCH=""+PKG_MGR=""SAFE_MODE=false-print_header() {- echo -e "${BLUE}"- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo " ServerKit Installer"- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"- echo -e "${NC}"+# ---------------------------------------------------------------------------+# Terminal styling+#+# Truecolor is used when the stream is an interactive terminal that has not+# opted out. The ServerKit identity is a violet ramp (V1 brightest .. V5+# deepest); status colors sit alongside it. Everything degrades to plain text+# when colour is unavailable so piped logs stay readable.+# ---------------------------------------------------------------------------+if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != "dumb" ]; then+ ESC=$'\033'+ RST="${ESC}[0m"; BLD="${ESC}[1m"; DIMM="${ESC}[2m"+ paint() { printf '%s[38;2;%d;%d;%dm' "$ESC" "$1" "$2" "$3"; }+else+ RST=''; BLD=''; DIMM=''+ paint() { :; }+fi++V1="$(paint 196 181 253)"; V2="$(paint 167 139 250)"; V3="$(paint 139 92 246)"+V4="$(paint 124 58 237)"; V5="$(paint 109 40 217)"+PAPER="$(paint 237 233 254)"; ASH="$(paint 165 160 190)"; FOG="$(paint 113 108 140)"+HUE_OK="$(paint 52 211 153)"; HUE_WARN="$(paint 250 204 21)"+HUE_ERR="$(paint 248 113 113)"; HUE_LINK="$(paint 103 232 249)"++# Line-level reporting. Distinct verbs, distinct marks, single indent.+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"; }+faint() { printf ' %s%s%s\n' "$FOG" "$1" "$RST"; }++# ---------------------------------------------------------------------------+# Phase headers+#+# Each major stage prints a numbered, time-stamped header followed by a violet+# rule. There is no global step total — the index plus elapsed clock is enough+# to read progress, and it never drifts out of sync with the actual path taken+# (source vs. release installs run different stages).+# ---------------------------------------------------------------------------+STARTED_AT=0+PHASE_N=0++clock() {+ [ "$STARTED_AT" -gt 0 ] || { printf ''; return; }+ local secs=$(( $(date +%s) - STARTED_AT ))+ printf '%dm %02ds' "$((secs / 60))" "$((secs % 60))"}-print_success() { echo -e "${GREEN}✓ $1${NC}"; }-print_error() { echo -e "${RED}✗ $1${NC}"; }-print_warning() { echo -e "${YELLOW}! $1${NC}"; }-print_info() { echo -e "${BLUE}→ $1${NC}"; }+phase() {+ PHASE_N=$((PHASE_N + 1))+ local t; t="$(clock)"+ printf '\n %s%s%02d%s %s%s%s %s%s%s\n' \+ "$BLD" "$V3" "$PHASE_N" "$RST" "$BLD" "$1" "$RST" "$FOG" "$t" "$RST"+ printf ' %s%s%s\n\n' "$V4" "──────────────────────────────────────" "$RST"+}-version_ge() { printf '%s\n%s' "$2" "$1" | sort -C -V; }-version_le() { printf '%s\n%s' "$1" "$2" | sort -C -V; }+# ---------------------------------------------------------------------------+# Masthead+# ---------------------------------------------------------------------------+masthead() {+ printf '\n'+ printf ' %s%s▖▌▌%s %s%sServerKit%s %sv%s%s %s•%s %s%s%s\n' \+ "$BLD" "$V2" "$RST" "$BLD" "$PAPER" "$RST" "$FOG" "$VERSION" "$RST" \+ "$HUE_OK" "$RST" "$ASH" "$CHANNEL" "$RST"+ printf ' %s%s▌▖▌%s %sSelf-hosted infrastructure, made simple.%s\n' \+ "$BLD" "$V3" "$RST" "$ASH" "$RST"+ printf ' %s%s▌▌▖%s %sWeb apps · Databases · Docker · Email · DNS · Security%s\n' \+ "$BLD" "$V4" "$RST" "$FOG" "$RST"+ printf ' %s%s▘▘▘%s %sPython + React, one command · serverkit.ai%s\n' \+ "$BLD" "$V5" "$RST" "$FOG" "$RST"+ printf '\n'+}-# Detect supported Python (3.11-3.12)-detect_python() {- if command -v python3 &>/dev/null; then- PY_VER=$(python3 -c 'import sys;print(".".join(map(str,sys.version_info[:2])))')- if version_ge "$PY_VER" "$PYTHON_MIN" && version_le "$PY_VER" "$PYTHON_MAX"; then- PYTHON_BIN="python3"- print_success "Using system Python $PY_VER"- return- fi+# ---------------------------------------------------------------------------+# Pre-flight: disk, memory, privileges+# ---------------------------------------------------------------------------+preflight() {+ step "Running pre-flight checks..."++ # Source builds need more headroom than unpacking a release.+ local need_kb=5242880+ [ "$INSTALL_FROM_RELEASE" = "1" ] && need_kb=2097152++ local free_kb+ free_kb=$(df /opt 2>/dev/null | awk 'NR==2 {print $4}')+ if [ -n "$free_kb" ] && [ "$free_kb" -lt "$need_kb" ]; then+ halt "Need at least $((need_kb / 1024 / 1024))GB free on /opt; less is available."fi- print_warning "System Python not in supported range ($PYTHON_MIN-$PYTHON_MAX)"-}-# Check RAM and enable safe mode for small VPS-check_ram() {- RAM=$(free -m | awk '/Mem:/ {print $2}')- if [ "$RAM" -le 700 ]; then- SAFE_MODE=true- print_warning "Low RAM detected (${RAM}MB) → enabling VPS Safe Mode"+ local free_mem+ free_mem=$(free -m | awk '/^Mem:/ {print $7}')+ if [ -n "$free_mem" ] && [ "$free_mem" -lt 256 ]; then+ warn "Under 256MB memory free — the install may run slowly."fi-}-# Create swap if system has very little-setup_swap() {- SWAP_TOTAL=$(free -m | awk '/^Swap:/ {print $2}')- if [ "$SWAP_TOTAL" -lt 512 ]; then- print_info "Creating swap space (1GB)..."- if [ ! -f /swapfile ]; then- fallocate -l 1G /swapfile 2>/dev/null || dd if=/dev/zero of=/swapfile bs=1M count=1024 status=none- chmod 600 /swapfile- mkswap /swapfile >/dev/null- fi- swapon /swapfile 2>/dev/null || true- print_success "Swap enabled"+ if [ "$EUID" -ne 0 ]; then+ halt "Please run this installer as root (use sudo)."fi++ good "Pre-flight checks passed."}-print_header+# ---------------------------------------------------------------------------+# Identify the OS family and CPU architecture+# ---------------------------------------------------------------------------+identify_system() {+ phase "Detecting System"-# Check if running as root-if [ "$EUID" -ne 0 ]; then- print_error "Please run as root (sudo)"- exit 1-fi+ [ -f /etc/os-release ] || halt "Cannot detect OS — /etc/os-release is missing."+ . /etc/os-release-# Enable low-RAM protections early (needs root for swap)-check_ram-setup_swap+ case "${ID:-}" in+ ubuntu|debian)+ OS_FAMILY="debian"; good "Detected: $PRETTY_NAME" ;;+ fedora)+ OS_FAMILY="fedora"; good "Detected: $PRETTY_NAME" ;;+ rocky|almalinux|rhel|centos)+ OS_FAMILY="rhel"; good "Detected: $PRETTY_NAME (RHEL family)" ;;+ *)+ warn "Untested OS '${ID:-unknown}' — continuing anyway." ;;+ esac++ ARCH=$(uname -m)+ case "$ARCH" in+ x86_64) DL_ARCH="amd64"; good "Architecture: x86_64" ;;+ aarch64|arm64) DL_ARCH="arm64"; good "Architecture: ARM64" ;;+ *) halt "Unsupported architecture: $ARCH" ;;+ esac+}-# Detect OS family-OS_FAMILY="unknown"-if [ -f /etc/os-release ]; then- . /etc/os-release- if [ "$ID" = "ubuntu" ] || [ "$ID" = "debian" ]; then- OS_FAMILY="debian"- elif [ "$ID" = "fedora" ]; then- OS_FAMILY="fedora"- elif [ "$ID" = "rocky" ] || [ "$ID" = "almalinux" ] || [ "$ID" = "rhel" ] || [ "$ID" = "centos" ]; then- # Rocky / Alma / RHEL / CentOS share dnf + the docker-ce rhel repo.- OS_FAMILY="rhel"+# ---------------------------------------------------------------------------+# Package manager abstraction (apt / dnf / yum)+# ---------------------------------------------------------------------------+choose_pkg_manager() {+ if command -v apt-get &>/dev/null; then+ PKG_MGR="apt"+ # unattended-upgrades can hold the dpkg lock right after boot; tell+ # apt to wait for it rather than failing outright.+ mkdir -p /etc/apt/apt.conf.d+ cat > /etc/apt/apt.conf.d/99-serverkit-lock-wait.conf <<'APT_EOF'+DPkg::Lock::Timeout "300";+APT_EOF+ elif command -v dnf &>/dev/null; then+ PKG_MGR="dnf"+ elif command -v yum &>/dev/null; then+ PKG_MGR="yum"else- print_warning "Unsupported OS ($ID). This script is designed for Ubuntu/Debian/Fedora/Rocky."+ halt "No supported package manager found (need apt, dnf, or yum)."fi-else- print_warning "Cannot detect OS. Proceeding with caution."-fi+}-echo ""-print_info "Installing system dependencies..."+refresh_pkg_index() {+ case "$PKG_MGR" in+ apt) apt-get update -y >/dev/null 2>&1 ;;+ dnf) dnf makecache --refresh >/dev/null 2>&1 ;;+ yum) yum makecache --refresh >/dev/null 2>&1 ;;+ esac+}-if [ "$OS_FAMILY" = "debian" ] || [ "$OS_FAMILY" = "unknown" ]; then- # Configure needrestart for non-interactive mode (Ubuntu 22.04+)- # This prevents the "Which services should be restarted?" dialog- # and avoids dpkg lock issues during automated installs- export NEEDRESTART_MODE=a- export DEBIAN_FRONTEND=noninteractive+pkg_add() {+ local out rc+ case "$PKG_MGR" in+ apt) out=$(apt-get install -y "$@" 2>&1) ;;+ dnf) out=$(dnf install -y "$@" 2>&1) ;;+ yum) out=$(yum install -y "$@" 2>&1) ;;+ esac+ rc=$?+ if [ $rc -ne 0 ]; then+ warn "Could not install: $* (exit $rc)"+ printf '%s\n' "$out" | tail -5 >&2+ return $rc+ fi+}- # Also configure needrestart.conf if it exists for future apt operations- if [ -f /etc/needrestart/needrestart.conf ]; then- sed -i "s/#\$nrconf{restart} = 'i';/\$nrconf{restart} = 'a';/" /etc/needrestart/needrestart.conf 2>/dev/null || true+# ---------------------------------------------------------------------------+# Memory tuning: low-RAM safe mode and a swap fallback+# ---------------------------------------------------------------------------+gauge_memory() {+ local total+ total=$(free -m | awk '/^Mem:/ {print $2}')+ if [ "$total" -le 700 ]; then+ SAFE_MODE=true+ warn "Low RAM (${total}MB) — enabling VPS safe mode."+ else+ SAFE_MODE=falsefi+}- apt-get update+ensure_swap() {+ local swap+ swap=$(free -m | awk '/^Swap:/ {print $2}')+ if [ "$swap" -lt 512 ]; then+ step "Adding 1GB of swap..."+ if [ ! -f /swapfile ]; then+ fallocate -l 1G /swapfile 2>/dev/null || \+ dd if=/dev/zero of=/swapfile bs=1M count=1024 status=none+ chmod 600 /swapfile+ mkswap /swapfile >/dev/null+ fi+ swapon /swapfile 2>/dev/null || true+ good "Swap active."+ fi+}+# ---------------------------------------------------------------------------+# Python 3.11/3.12 — detect a usable interpreter or build one+# ---------------------------------------------------------------------------+ver_in_range() {+ # true when $1 is >= PYTHON_MIN and <= PYTHON_MAX+ printf '%s\n%s' "$PYTHON_MIN" "$1" | sort -C -V && \+ printf '%s\n%s' "$1" "$PYTHON_MAX" | sort -C -V+}- apt-get install -y \- python3 \- python3-pip \- python3-venv \- python3-dev \- git \- curl \- build-essential \- libffi-dev \- libssl-dev \- iproute2 \- procps+locate_python() {+ if command -v python3 &>/dev/null; then+ local v+ v=$(python3 -c 'import sys;print(".".join(map(str,sys.version_info[:2])))')+ if ver_in_range "$v"; then+ PYTHON_BIN="python3"+ good "Using system Python $v"+ return+ fi+ fi+ warn "System Python is outside the supported $PYTHON_MIN–$PYTHON_MAX range."+}++build_python_from_source() {+ cd /tmp+ wget -q https://www.python.org/ftp/python/3.12.8/Python-3.12.8.tgz+ tar xzf Python-3.12.8.tgz+ cd Python-3.12.8+ ./configure --enable-optimizations --prefix=/usr/local 2>&1 | tail -1+ make -j"$(nproc)" 2>&1 | tail -1+ make altinstall 2>&1 | tail -1+ cd /tmp && rm -rf Python-3.12.8 Python-3.12.8.tgz+}- detect_python+provision_python() {+ phase "Installing Python"- # If system Python is out of supported range, install 3.12- if [ -z "$PYTHON_BIN" ]; then- print_info "Installing Python 3.12..."+ locate_python+ [ -n "$PYTHON_BIN" ] && return+ step "Installing Python 3.12..."+ if [ "$OS_FAMILY" = "debian" ]; thenif [ "$ID" = "ubuntu" ]; then- # Ubuntu: use deadsnakes PPA- apt-get install -y software-properties-common+ pkg_add software-properties-commonadd-apt-repository -y ppa:deadsnakes/ppa- apt-get update- apt-get install -y python3.12 python3.12-venv python3.12-dev- PYTHON_BIN="python3.12"+ refresh_pkg_index+ pkg_add python3.12 python3.12-venv python3.12-develse- # Debian / other apt-based: build from source- print_info "Building Python 3.12 from source (this may take a few minutes)..."- apt-get install -y wget zlib1g-dev libbz2-dev libreadline-dev \+ step "Compiling Python 3.12 from source (a few minutes)..."+ pkg_add wget zlib1g-dev libbz2-dev libreadline-dev \libsqlite3-dev libncurses5-dev libncursesw5-dev \- xz-utils tk-dev liblzma-dev- cd /tmp- wget -q https://www.python.org/ftp/python/3.12.8/Python-3.12.8.tgz- tar xzf Python-3.12.8.tgz- cd Python-3.12.8- ./configure --enable-optimizations --prefix=/usr/local 2>&1 | tail -1- make -j"$(nproc)" 2>&1 | tail -1- make altinstall 2>&1 | tail -1- cd /tmp && rm -rf Python-3.12.8 Python-3.12.8.tgz- PYTHON_BIN="python3.12"+ xz-utils tk-dev liblzma-dev libffi-dev libssl-dev+ build_python_from_sourcefi-- if ! command -v "$PYTHON_BIN" &>/dev/null; then- print_error "Failed to install Python 3.12. Please install Python 3.11 or 3.12 manually."- exit 1- fi- print_success "Python 3.12 installed"- fi--elif [ "$OS_FAMILY" = "fedora" ] || [ "$OS_FAMILY" = "rhel" ]; then- # Rocky/Alma/RHEL need EPEL for some packages (python3.12 on RHEL 9, etc.)- if [ "$OS_FAMILY" = "rhel" ] && ! rpm -q epel-release >/dev/null 2>&1; then- dnf install -y epel-release || true- fi-- dnf makecache --refresh-- # On Rocky/RHEL 9.7+, the updates stream ships openssl-libs 3.5.x- # which has a different ABI than the older openssl-3.0.x most boxes- # ship with. If subsequent dnf installs pull in the new openssl-libs- # as a transitive dep (e.g. via libcurl from `dnf install curl`),- # every new sshd fork dies with "OpenSSL version mismatch" — TCP- # accepts, then RST, and remote installs over SSH fail silently.- # Pull openssh + openssl in the same transaction up front so the- # post-transaction scriptlet restarts sshd against a matched- # openssh-server/openssl-libs pair. sshd.service uses- # KillMode=process so existing SSH sessions survive the restart.- if [ "$OS_FAMILY" = "rhel" ]; then- dnf upgrade -y openssh openssh-server openssh-clients \- openssl openssl-libs openssl-devel 2>/dev/null || true- fi-- dnf install -y \- python3 \- python3-pip \- python3-devel \- git \- curl \- gcc \- gcc-c++ \- make \- libffi-devel \- openssl-devel \- python3-devel \- iproute \- procps-ng-- detect_python-- if [ -z "$PYTHON_BIN" ]; then- print_info "Installing Python 3.12..."- if dnf install -y python3.12 python3.12-devel 2>/dev/null; then- PYTHON_BIN="python3.12"- else- # Fallback: build from source- print_info "Building Python 3.12 from source (this may take a few minutes)..."- dnf install -y wget zlib-devel bzip2-devel readline-devel \+ PYTHON_BIN="python3.12"+ elif [ "$OS_FAMILY" = "fedora" ] || [ "$OS_FAMILY" = "rhel" ]; then+ if ! pkg_add python3.12 python3.12-devel; then+ step "Compiling Python 3.12 from source (a few minutes)..."+ pkg_add wget zlib-devel bzip2-devel readline-devel \sqlite-devel ncurses-devel xz-devel tk-devel libffi-devel- cd /tmp- wget -q https://www.python.org/ftp/python/3.12.8/Python-3.12.8.tgz- tar xzf Python-3.12.8.tgz- cd Python-3.12.8- ./configure --enable-optimizations --prefix=/usr/local 2>&1 | tail -1- make -j"$(nproc)" 2>&1 | tail -1- make altinstall 2>&1 | tail -1- cd /tmp && rm -rf Python-3.12.8 Python-3.12.8.tgz- PYTHON_BIN="python3.12"+ build_python_from_sourcefi-- if ! command -v "$PYTHON_BIN" &>/dev/null; then- print_error "Failed to install Python 3.12. Please install Python 3.11 or 3.12 manually."- exit 1- fi- print_success "Python 3.12 installed"+ PYTHON_BIN="python3.12"fi-fi-print_success "System dependencies installed"+ command -v "$PYTHON_BIN" &>/dev/null || \+ halt "Could not install Python 3.12 — install Python 3.11 or 3.12 by hand."+ good "Python 3.12 installed."+}-# Install Docker if not present.-#-# Why not just `curl get.docker.com | sh` on Fedora/RHEL?-# Docker recently added `docker-model-plugin` to that script's package-# list, but the package only ships in the docker-ce apt repos — on-# Fedora/RHEL dnf, the install aborts with "Unable to find a match:-# docker-model-plugin". We add the repo and install the core packages-# explicitly to avoid that.-if ! command -v docker &> /dev/null; then- print_info "Installing Docker..."-- if [ "$OS_FAMILY" = "fedora" ]; then- dnf install -y dnf-plugins-core- dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo- dnf install -y docker-ce docker-ce-cli containerd.io \- docker-compose-plugin docker-buildx-plugin- elif [ "$OS_FAMILY" = "rhel" ]; then- dnf install -y dnf-plugins-core- dnf config-manager --add-repo https://download.docker.com/linux/rhel/docker-ce.repo- dnf install -y docker-ce docker-ce-cli containerd.io \- docker-compose-plugin docker-buildx-plugin- else- curl -fsSL https://get.docker.com | sh+# ---------------------------------------------------------------------------+# Docker engine + compose plugin+# ---------------------------------------------------------------------------+provision_docker() {+ phase "Docker"++ if command -v docker &>/dev/null; then+ good "Docker already present: $(docker --version | head -1)"+ returnfi+ step "Installing Docker..."+ case "$OS_FAMILY" in+ fedora)+ pkg_add dnf-plugins-core+ dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo+ pkg_add docker-ce docker-ce-cli containerd.io docker-compose-plugin docker-buildx-plugin+ ;;+ rhel)+ pkg_add dnf-plugins-core+ dnf config-manager --add-repo https://download.docker.com/linux/rhel/docker-ce.repo+ pkg_add docker-ce docker-ce-cli containerd.io docker-compose-plugin docker-buildx-plugin+ ;;+ *)+ curl -fsSL https://get.docker.com | sh+ ;;+ esac+systemctl enable dockersystemctl start docker- print_success "Docker installed"-else- print_success "Docker already installed"-fi+ good "Docker installed."+}-# Install Docker Compose plugin if not present (Debian/Ubuntu only — the-# RHEL-family install above already pulled it in via the docker-ce repo).-if ! docker compose version &> /dev/null; then- print_info "Installing Docker Compose..."- if [ "$OS_FAMILY" = "fedora" ] || [ "$OS_FAMILY" = "rhel" ]; then- dnf install -y docker-compose-plugin+ensure_compose_plugin() {+ if docker compose version &>/dev/null; then+ good "Docker Compose plugin present."+ return+ fi+ step "Installing Docker Compose plugin..."+ pkg_add docker-compose-plugin+ good "Docker Compose plugin installed."+}++# ---------------------------------------------------------------------------+# Node.js 20 (only needed for source builds — releases ship a built frontend)+# ---------------------------------------------------------------------------+provision_node() {+ phase "Node.js"++ if [ "$INSTALL_FROM_RELEASE" = "1" ]; then+ good "Skipping Node.js — the release ships a pre-built frontend."+ return+ fi++ if command -v node &>/dev/null; then+ good "Node.js already present: $(node --version)"+ return+ fi++ step "Installing Node.js 20 LTS..."+ if [ "$OS_FAMILY" = "debian" ]; then+ curl -fsSL https://deb.nodesource.com/setup_20.x | bash - >/dev/null 2>&1else- apt-get install -y docker-compose-plugin+ curl -fsSL https://rpm.nodesource.com/setup_20.x | bash - >/dev/null 2>&1fi- print_success "Docker Compose installed"-else- print_success "Docker Compose already installed"-fi+ pkg_add nodejs+ good "Node.js $(node --version) installed."+}++# ---------------------------------------------------------------------------+# Release tarball path+# ---------------------------------------------------------------------------+resolve_release_tag() {+ if [ -n "$SERVERKIT_VERSION" ]; then+ printf '%s' "$SERVERKIT_VERSION"+ return+ fi+ curl -sf "https://api.github.com/repos/${GITHUB_REPO}/releases/latest" \+ | grep '"tag_name"' | head -1 | cut -d'"' -f4+}++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 base="https://github.com/${GITHUB_REPO}/releases/download/${tag}"+ local 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 "Unpacking release..."+ rm -rf "$INSTALL_DIR"+ mkdir -p "$(dirname "$INSTALL_DIR")"+ tar xzf "$tarball" -C "$(dirname "$INSTALL_DIR")"+ rm -f "$tarball"+ good "Release unpacked into $INSTALL_DIR"+}-# Install Node.js for frontend build (builds on host to avoid Docker memory issues)-if ! command -v node &> /dev/null; then- print_info "Installing Node.js..."- if [ "$OS_FAMILY" = "fedora" ] || [ "$OS_FAMILY" = "rhel" ]; then- curl -fsSL https://rpm.nodesource.com/setup_20.x | bash -- dnf install -y nodejs+# ---------------------------------------------------------------------------+# Source path: fetch / refresh the repository+# ---------------------------------------------------------------------------+sync_source() {+ phase "Source Code"++ if [ -d "$INSTALL_DIR/.git" ]; then+ step "Refreshing the existing checkout..."+ cd "$INSTALL_DIR"+ if ! git pull --ff-only; then+ warn "Fast-forward failed (local edits?) — hard-resetting to origin/main."+ git fetch origin+ git reset --hard origin/main+ fielse- curl -fsSL https://deb.nodesource.com/setup_20.x | bash -- apt-get install -y nodejs+ step "Cloning ServerKit..."+ rm -rf "$INSTALL_DIR"+ git clone --depth 1 "https://github.com/${GITHUB_REPO}.git" "$INSTALL_DIR"+ cd "$INSTALL_DIR"fi- print_success "Node.js $(node --version) installed"-else- print_success "Node.js $(node --version) already installed"-fi+ good "Repository ready."+}-# Clone or update repository-print_info "Installing ServerKit to $INSTALL_DIR..."+# ---------------------------------------------------------------------------+# On-disk layout+# ---------------------------------------------------------------------------+make_directories() {+ phase "Creating Directories"++ local d+ for d in "$LOG_DIR" "$DATA_DIR" "$BACKUP_DIR" "$CONFIG_DIR" "$INSTALL_DIR/backend/instance"; do+ mkdir -p -m 0750 "$d"+ done+ for d in "$INSTALL_DIR/nginx/ssl" /etc/serverkit/templates /var/serverkit/apps \+ /var/www/acme /etc/nginx/serverkit-locations; do+ mkdir -p -m 0755 "$d"+ done++ good "Directories created."+}-if [ -d "$INSTALL_DIR" ]; then- print_warning "Directory exists, updating..."- cd "$INSTALL_DIR"- git fetch origin- git reset --hard origin/main-else- git clone https://github.com/jhd3197/serverkit.git "$INSTALL_DIR"- cd "$INSTALL_DIR"-fi+# ---------------------------------------------------------------------------+# Python virtual environment + dependencies+# ---------------------------------------------------------------------------+build_virtualenv() {+ phase "Python Environment"-print_success "Repository cloned"--# Create directories-print_info "Creating directories..."-mkdir -p "$LOG_DIR"-mkdir -p "$DATA_DIR"-mkdir -p "$INSTALL_DIR/backend/instance"-mkdir -p "$INSTALL_DIR/nginx/ssl"-mkdir -p /etc/serverkit/templates-mkdir -p /var/serverkit/apps--# Copy bundled templates to system directory-print_info "Installing app templates..."-if [ -d "$INSTALL_DIR/backend/templates" ]; then- 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- print_success "Installed $(ls /etc/serverkit/templates/*.yaml 2>/dev/null | wc -l) app templates"-fi+ step "Creating the virtual environment..."+ $PYTHON_BIN -m venv "$VENV_DIR"+ source "$VENV_DIR/bin/activate"-# Set up Python virtual environment-print_info "Setting up Python virtual environment..."-$PYTHON_BIN -m venv "$VENV_DIR"-source "$VENV_DIR/bin/activate"+ step "Installing Python dependencies..."+ pip install --upgrade pip --quiet+ if [ "$SAFE_MODE" = true ]; then+ pip install --no-cache-dir -r "$INSTALL_DIR/backend/requirements.txt" --quiet+ else+ pip install -r "$INSTALL_DIR/backend/requirements.txt" --quiet+ fi+ pip install gunicorn gevent gevent-websocket --quiet-# Install Python dependencies-print_info "Installing Python dependencies..."-pip install --upgrade pip-if [ "$SAFE_MODE" = true ]; then- pip install --no-cache-dir -r "$INSTALL_DIR/backend/requirements.txt"-else- pip install -r "$INSTALL_DIR/backend/requirements.txt"-fi-pip install gunicorn gevent gevent-websocket+ good "Python environment ready."+}-print_success "Python dependencies installed"+# ---------------------------------------------------------------------------+# Application configuration and generated secrets+# ---------------------------------------------------------------------------+write_config() {+ phase "Configuration"-# Generate .env if not exists-if [ ! -f "$INSTALL_DIR/.env" ]; then- print_info "Generating configuration..."- SECRET_KEY=$(openssl rand -hex 32)- JWT_SECRET_KEY=$(openssl rand -hex 32)+ if [ -f "$INSTALL_DIR/.env" ]; then+ warn ".env already exists — leaving the current configuration in place."+ return+ fi- cat > "$INSTALL_DIR/.env" << EOF+ step "Generating configuration..."+ local secret_key jwt_secret encryption_key+ secret_key=$(openssl rand -hex 32)+ jwt_secret=$(openssl rand -hex 32)+ encryption_key=$(python3 -c 'import base64, os; print(base64.urlsafe_b64encode(os.urandom(32)).decode())')++ # Widen CORS / advertise a public URL when a panel domain is known.+ local public_url="" cors_origins="http://localhost,https://localhost"+ if [ -n "$PANEL_DOMAIN" ]; then+ public_url="http://$PANEL_DOMAIN"+ cors_origins="http://localhost,https://localhost,http://$PANEL_DOMAIN,https://$PANEL_DOMAIN"+ fi++ cat > "$INSTALL_DIR/.env" <<EOF# ServerKit Configuration# Generated on $(date)# Security Keys (auto-generated, keep secret!)-SECRET_KEY=$SECRET_KEY-JWT_SECRET_KEY=$JWT_SECRET_KEY+SECRET_KEY=$secret_key+JWT_SECRET_KEY=$jwt_secret+SERVERKIT_ENCRYPTION_KEY=$encryption_key# Database (SQLite by default)DATABASE_URL=sqlite:///$INSTALL_DIR/backend/instance/serverkit.db# CORS Origins (comma-separated, add your domain)-CORS_ORIGINS=http://localhost,https://localhost+CORS_ORIGINS=$cors_origins++# Public URL for agents and install commands (optional)+${public_url:+# SERVERKIT_PUBLIC_URL=$public_url}# PortsPORT=80@@ -393,173 +540,364 @@ SSL_PORT=443# EnvironmentFLASK_ENV=productionEOF+ chmod 600 "$INSTALL_DIR/.env"+ good "Configuration generated."++ # When a domain is configured, bounce bare-IP visitors to it.+ if [ -n "$PANEL_DOMAIN" ]; then+ mkdir -p /etc/nginx/serverkit-conf.d+ cat > /etc/nginx/serverkit-conf.d/canonical-domain.conf <<EOF+# Auto-generated by ServerKit install.sh+# Redirect direct IP access to the canonical panel domain.+server {+ listen 80 default_server;+ server_name _;+ if (\$host ~* ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+\$) {+ return 301 http://$PANEL_DOMAIN\$request_uri;+ }+}+EOF+ good "Canonical-domain redirect configured for $PANEL_DOMAIN"+ fi+}- print_success "Configuration generated"-else- print_warning ".env already exists, keeping existing configuration"-fi+# ---------------------------------------------------------------------------+# Self-signed certificate placeholder+# ---------------------------------------------------------------------------+seed_self_signed_cert() {+ phase "SSL Certificate"-# Generate self-signed SSL certificate if not exists-if [ ! -f "$INSTALL_DIR/nginx/ssl/fullchain.pem" ]; then- print_info "Generating self-signed SSL certificate..."+ if [ -f "$INSTALL_DIR/nginx/ssl/fullchain.pem" ]; then+ good "SSL certificate already present."+ return+ fi++ step "Creating a self-signed certificate..."openssl req -x509 -nodes -days 365 -newkey rsa:2048 \-keyout "$INSTALL_DIR/nginx/ssl/privkey.pem" \-out "$INSTALL_DIR/nginx/ssl/fullchain.pem" \-subj "/CN=localhost" 2>/dev/null- print_warning "Self-signed certificate created. Replace with real cert for production."-fi+ warn "Self-signed cert in place — swap in a real certificate for production."+}-# Install systemd service for backend-print_info "Installing systemd service..."-cp "$INSTALL_DIR/serverkit-backend.service" /etc/systemd/system/serverkit.service+# ---------------------------------------------------------------------------+# Frontend build (skipped on release installs)+# ---------------------------------------------------------------------------+build_frontend() {+ phase "Frontend Build"-# Reload systemd and enable service-systemctl daemon-reload-systemctl enable serverkit+ if [ "$INSTALL_FROM_RELEASE" = "1" ]; then+ good "Using the pre-built frontend from the release."+ return+ fi-print_success "Systemd service installed"+ step "Installing npm packages..."+ cd "$INSTALL_DIR/frontend"+ npm ci --prefer-offline 2>&1 | tail -3-# Make CLI executable and create symlink-chmod +x "$INSTALL_DIR/serverkit"-ln -sf "$INSTALL_DIR/serverkit" /usr/local/bin/serverkit+ step "Compiling the frontend bundle..."+ NODE_OPTIONS="--max-old-space-size=1024" npm run build 2>&1 | tail -5+ good "Frontend built."+}-print_success "CLI installed"+# ---------------------------------------------------------------------------+# nginx site + reverse-proxy wiring+# ---------------------------------------------------------------------------+configure_nginx() {+ phase "Nginx"-# Install and configure host nginx as reverse proxy-print_info "Setting up nginx reverse proxy..."-if [ "$OS_FAMILY" = "fedora" ] || [ "$OS_FAMILY" = "rhel" ]; then- dnf install -y nginx-else- apt-get install -y nginx-fi+ if command -v nginx &>/dev/null; then+ good "Nginx already installed."+ else+ step "Installing Nginx..."+ pkg_add nginx+ systemctl enable nginx+ good "Nginx installed."+ fi-# Stop nginx and remove default site-systemctl stop nginx 2>/dev/null || true-rm -f /etc/nginx/sites-enabled/default+ systemctl stop nginx 2>/dev/null || true+ rm -f /etc/nginx/sites-enabled/default-# Ensure sites directories exist-mkdir -p /etc/nginx/sites-available-mkdir -p /etc/nginx/sites-enabled-mkdir -p /etc/nginx/serverkit-locations+ mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /etc/nginx/serverkit-conf.d-# Ensure nginx.conf includes sites-enabled (Fedora uses conf.d by default)-if ! grep -q "sites-enabled" /etc/nginx/nginx.conf; then- sed -i '/http {/a \ include /etc/nginx/sites-enabled/*;' /etc/nginx/nginx.conf-fi+ # Fedora/RHEL nginx.conf doesn't include sites-enabled by default.+ if ! grep -q "sites-enabled" /etc/nginx/nginx.conf; then+ sed -i '/http {/a \ include /etc/nginx/sites-enabled/*;' /etc/nginx/nginx.conf+ fi-# Remove any nginx configs that use server_name _ (catch-all) besides serverkit-managed ones-# These conflict with the panel and can allow compromised apps to hijack all traffic-for conf in /etc/nginx/sites-enabled/*; do- [ -f "$conf" ] || continue- name=$(basename "$conf")- # Skip all ServerKit-managed configs- case "$name" in serverkit-*|serverkit.conf) 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--# Install ServerKit site config-cp "$INSTALL_DIR/nginx/sites-available/serverkit.conf" /etc/nginx/sites-available/-ln -sf /etc/nginx/sites-available/serverkit.conf /etc/nginx/sites-enabled/--# Copy site template-cp "$INSTALL_DIR/nginx/sites-available/example.conf.template" /etc/nginx/sites-available/--# Configure SELinux to allow nginx reverse proxying (Fedora/Rocky/RHEL)-if { [ "$OS_FAMILY" = "fedora" ] || [ "$OS_FAMILY" = "rhel" ]; } && command -v setsebool &> /dev/null; then- setsebool -P httpd_can_network_connect 1 2>/dev/null || true-fi+ # Drop any foreign catch-all vhost that would shadow the panel.+ for conf in /etc/nginx/sites-enabled/*; do+ [ -f "$conf" ] || continue+ local name; name=$(basename "$conf")+ case "$name" in serverkit-*|serverkit.conf) continue ;; esac+ if grep -Eq 'server_name[[:space:]]+_;' "$conf" 2>/dev/null; then+ warn "Removing conflicting catch-all vhost: $name"+ rm -f "/etc/nginx/sites-enabled/$name" "/etc/nginx/sites-available/$name"+ fi+ done-print_success "Nginx proxy configured"+ cp "$INSTALL_DIR/nginx/sites-available/serverkit.conf" /etc/nginx/sites-available/+ ln -sf /etc/nginx/sites-available/serverkit.conf /etc/nginx/sites-enabled/+ cp "$INSTALL_DIR/nginx/sites-available/example.conf.template" /etc/nginx/sites-available/-# Clean up Docker to prevent issues-print_info "Cleaning up Docker..."-docker network prune -f 2>/dev/null || true-docker container prune -f 2>/dev/null || true+ # SELinux: let nginx make upstream connections to the app containers.+ if { [ "$OS_FAMILY" = "fedora" ] || [ "$OS_FAMILY" = "rhel" ]; } && command -v setsebool &>/dev/null; then+ setsebool -P httpd_can_network_connect 1 2>/dev/null || true+ fi-# Ensure swap exists for low-RAM VPS servers (Vite build needs ~512MB+)-setup_swap+ good "Nginx configured."+}-# Build frontend on host (avoids Docker memory overhead on low-RAM VPS)-print_info "Building frontend..."-cd "$INSTALL_DIR/frontend"-npm ci --prefer-offline 2>&1 | tail -1-NODE_OPTIONS="--max-old-space-size=1024" npm run build-print_success "Frontend built"+# ---------------------------------------------------------------------------+# systemd unit + CLI symlink+# ---------------------------------------------------------------------------+install_service() {+ phase "Systemd Service"-# Package frontend into nginx container-print_info "Building frontend container..."-cd "$INSTALL_DIR"-docker compose build+ cp "$INSTALL_DIR/serverkit-backend.service" /etc/systemd/system/serverkit.service+ chmod 644 /etc/systemd/system/serverkit.service-print_info "Starting services..."+ chmod +x "$INSTALL_DIR/serverkit"+ ln -sf "$INSTALL_DIR/serverkit" /usr/local/bin/serverkit-# Start backend (systemd)-systemctl start serverkit+ systemctl daemon-reload+ systemctl enable serverkit+ good "Systemd service installed."+}-# Start frontend (Docker)-docker compose up -d+# ---------------------------------------------------------------------------+# App templates+# ---------------------------------------------------------------------------+sync_templates() {+ phase "App Templates"-# Start nginx-systemctl start nginx-systemctl enable nginx+ if [ -d "$INSTALL_DIR/backend/templates" ]; then+ 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+ good "Installed $(ls /etc/serverkit/templates/*.yaml 2>/dev/null | wc -l) app templates."+ else+ warn "No app templates found."+ fi+}-# Wait for services to start-print_info "Waiting for services to start..."-sleep 10+# ---------------------------------------------------------------------------+# Bring services up+# ---------------------------------------------------------------------------+launch_services() {+ phase "Starting Services"-# Health check-echo ""-BACKEND_OK=false-FRONTEND_OK=false+ step "Pruning stale Docker networks..."+ docker network prune -f 2>/dev/null || true+ docker container prune -f 2>/dev/null || true-if curl -s http://127.0.0.1:5000/api/v1/system/health > /dev/null 2>&1; then- BACKEND_OK=true- print_success "Backend is running"-else- print_error "Backend health check failed"-fi+ step "Building the frontend container..."+ cd "$INSTALL_DIR"+ docker compose build 2>&1 | tail -5-if curl -s http://localhost > /dev/null 2>&1; then- FRONTEND_OK=true- print_success "Frontend is running"-else- print_error "Frontend health check failed"-fi+ step "Starting the backend..."+ systemctl start serverkit-echo ""-if [ "$BACKEND_OK" = true ] && [ "$FRONTEND_OK" = true ]; then- # Track successful install- INSTALLED_VERSION=$(cat "$INSTALL_DIR/VERSION" 2>/dev/null | tr -d '\n\r ')- curl -s "https://serverkit.ai/track/install?v=${INSTALLED_VERSION}" >/dev/null 2>&1 || true-- echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"- echo -e "${GREEN} Installation Complete!${NC}"- echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"- echo ""- echo "ServerKit is now running at: http://localhost"- echo ""- echo "Quick Start:"- echo " 1. Create admin user: serverkit create-admin"- echo " 2. View status: serverkit status"- echo " 3. View logs: serverkit logs"- echo ""- echo "Service Management:"- echo " Backend (systemd): systemctl [start|stop|restart] serverkit"- echo " Frontend (Docker): docker compose --project-directory $INSTALL_DIR [up|down]"- echo ""- echo "For all commands: serverkit help"- echo ""-else- echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"- echo -e "${RED} Installation may have issues${NC}"- echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"- echo ""- echo "Troubleshooting:"- echo " Backend logs: journalctl -u serverkit -f"- echo " Frontend logs: docker compose --project-directory $INSTALL_DIR logs -f"- echo ""-fi+ step "Starting the frontend container..."+ docker compose up -d 2>&1 | tail -5++ step "Starting nginx..."+ systemctl start nginx+ good "Services started."+}++# ---------------------------------------------------------------------------+# Health probe + automatic rollback+# ---------------------------------------------------------------------------+revert_install() {+ warn "Health check failed — rolling back..."++ systemctl stop serverkit 2>/dev/null || true+ systemctl 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."+ fi++ systemctl daemon-reload+ systemctl start serverkit 2>/dev/null || true+ systemctl start nginx 2>/dev/null || true+ halt "Install rolled back. Inspect logs: journalctl -u serverkit -n 50"+}++await_health() {+ phase "Health Check"++ step "Waiting for the backend to answer..."+ local 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."+ return 0+ fi+ sleep 2+ waited=$((waited + 2))+ done++ warn "Backend did not respond on port 5000."+ return 1+}++# ---------------------------------------------------------------------------+# Let's Encrypt for the panel domain+# ---------------------------------------------------------------------------+issue_panel_cert() {+ if [ -z "$PANEL_DOMAIN" ]; then+ good "No domain set — skipping SSL (panel reachable by IP)."+ return+ fi++ phase "Panel SSL Certificate"++ if ! command -v certbot &>/dev/null; then+ warn "Certbot is not installed — skipping SSL."+ return+ fi++ step "Requesting a Let's Encrypt certificate for $PANEL_DOMAIN..."+ if certbot --nginx -d "$PANEL_DOMAIN" --non-interactive --agree-tos \+ --register-unsafely-without-email --redirect 2>/dev/null; then+ good "Certificate issued for $PANEL_DOMAIN"+ else+ warn "Certbot failed — retry manually: certbot --nginx -d $PANEL_DOMAIN"+ fi+}++# ---------------------------------------------------------------------------+# Safety copy of an existing install before we touch it+# ---------------------------------------------------------------------------+snapshot_existing() {+ if [ -d "$INSTALL_DIR" ] && [ ! -d "$INSTALL_DIR.backup" ]; then+ step "Backing up the existing installation..."+ cp -a "$INSTALL_DIR" "$INSTALL_DIR.backup"+ good "Backup saved to $INSTALL_DIR.backup"+ fi+}++# ---------------------------------------------------------------------------+# Closing summary+# ---------------------------------------------------------------------------+print_outro() {+ local ip+ ip=$(curl -sf --max-time 5 https://api.ipify.org 2>/dev/null || \+ hostname -I 2>/dev/null | awk '{print $1}' || echo "YOUR_SERVER_IP")++ printf '\n'+ printf ' %s%s✔ ServerKit installed successfully%s %s%s%s\n' \+ "$BLD" "$HUE_OK" "$RST" "$FOG" "$(clock)" "$RST"+ printf ' %s%s%s\n\n' "$V4" "──────────────────────────────────────" "$RST"++ if [ -n "$PANEL_DOMAIN" ]; then+ printf ' %sPanel URL%s https://%s\n' "$BLD" "$RST" "$PANEL_DOMAIN"+ else+ printf ' %sPanel URL%s http://%s\n' "$BLD" "$RST" "$ip"+ fi+ printf ' %sFirst step%s create an admin user\n\n' "$BLD" "$RST"++ printf ' %sCLI%s serverkit status\n' "$BLD" "$RST"+ printf ' serverkit create-admin\n'+ printf ' serverkit --help\n\n'++ printf ' %sService%s systemctl status serverkit\n' "$BLD" "$RST"+ printf ' journalctl -u serverkit -f\n'+ printf ' systemctl restart serverkit\n\n'++ printf ' %sPaths%s install : %s\n' "$BLD" "$RST" "$INSTALL_DIR"+ printf ' config : %s/.env\n' "$INSTALL_DIR"+ printf ' backups : %s\n\n' "$BACKUP_DIR"++ printf ' %sUpdate%s sudo serverkit update\n\n' "$HUE_WARN" "$RST"+}++# ---------------------------------------------------------------------------+# Anonymous install ping (best-effort)+# ---------------------------------------------------------------------------+ping_telemetry() {+ local v+ v=$(cat "$INSTALL_DIR/VERSION" 2>/dev/null | tr -d '\n\r ')+ curl -s "https://serverkit.ai/track/install?v=${v}" >/dev/null 2>&1 || true+}++# ---------------------------------------------------------------------------+# Ask for a panel domain when running interactively+# ---------------------------------------------------------------------------+prompt_for_domain() {+ [ -z "$PANEL_DOMAIN" ] && [ -t 0 ] || return 0+ printf '\n'+ printf '%sEnter your panel domain (e.g. panel.example.com)%s\n' "$BLD" "$RST"+ printf 'Leave blank to access via IP\n'+ printf '%sTip:%s set PANEL_DOMAIN=... in the environment to skip this prompt\n' "$BLD" "$RST"+ printf '> '+ read -r PANEL_DOMAIN+ PANEL_DOMAIN=$(printf '%s' "$PANEL_DOMAIN" | tr -d ' ')+ [ -n "$PANEL_DOMAIN" ] && PANEL_PORT="80"+}++# ---------------------------------------------------------------------------+# Orchestration+# ---------------------------------------------------------------------------+main() {+ STARTED_AT=$(date +%s)+ masthead++ # Default to a release install unless a source tree is already present or+ # the caller forced a source build / pinned a version.+ if [ "$BUILD_FROM_SOURCE" != "1" ] && [ ! -d "$INSTALL_DIR/backend/src" ] && [ -z "${SERVERKIT_VERSION:-}" ]; then+ INSTALL_FROM_RELEASE=1+ fi++ identify_system+ choose_pkg_manager+ preflight+ gauge_memory+ ensure_swap+ prompt_for_domain+ snapshot_existing++ provision_docker+ ensure_compose_plugin+ provision_node++ if [ "$INSTALL_FROM_RELEASE" = "1" ]; then+ fetch_release || warn "Falling back to a source build."+ fi++ if [ "$INSTALL_FROM_RELEASE" != "1" ]; then+ provision_python+ sync_source+ make_directories+ build_virtualenv+ build_frontend+ else+ make_directories+ # The CLI needs a venv even on release installs.+ if [ ! -d "$VENV_DIR" ]; then+ provision_python+ build_virtualenv+ fi+ fi++ write_config+ seed_self_signed_cert+ sync_templates+ configure_nginx+ install_service++ # Tolerate failures through start + health so rollback can run.+ set +e+ launch_services+ await_health || revert_install+ issue_panel_cert+ set -e++ ping_telemetry+ print_outro+}++main "$@"diff --git a/scripts/build-release.sh b/scripts/build-release.shnew file mode 100644index 00000000..019f639d--- /dev/null+++ b/scripts/build-release.sh@@ -0,0 +1,126 @@+#!/bin/bash+#+# ServerKit release builder.+#+# Produces a portable tarball that installs without compiling on the target:+# the full /opt/serverkit tree with a pre-built venv and a built frontend.+#+# bash scripts/build-release.sh+# VERSION=v1.7.0 bash scripts/build-release.sh+#+set -euo pipefail++BUILD_DIR="/tmp/serverkit-release-build"++# ---------------------------------------------------------------------------+# Terminal styling (violet ServerKit identity, degrades to plain text)+# ---------------------------------------------------------------------------+if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != "dumb" ]; then+ ESC=$'\033'+ RST="${ESC}[0m"; BLD="${ESC}[1m"+ paint() { printf '%s[38;2;%d;%d;%dm' "$ESC" "$1" "$2" "$3"; }+else+ RST=''; BLD=''+ paint() { :; }+fi++HUE_OK="$(paint 52 211 153)"; HUE_ERR="$(paint 248 113 113)"+HUE_LINK="$(paint 103 232 249)"++good() { printf ' %s✔%s %s\n' "$HUE_OK" "$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"; }++# ---------------------------------------------------------------------------+# Resolve version + architecture into an output filename+# ---------------------------------------------------------------------------+if [ -n "${VERSION:-}" ]; then+ RELEASE_TAG="$VERSION"+elif [ -f "VERSION" ]; then+ RELEASE_TAG="v$(cat VERSION | tr -d '\n\r ')"+else+ halt "Cannot determine version. Set VERSION or create a VERSION file."+fi++case "$(uname -m)" in+ x86_64) DL_ARCH="amd64" ;;+ aarch64|arm64) DL_ARCH="arm64" ;;+ *) halt "Unsupported architecture: $(uname -m)" ;;+esac++OUTPUT="serverkit-${RELEASE_TAG}-linux-${DL_ARCH}.tar.gz"+step "Building release ${RELEASE_TAG} for ${DL_ARCH}"++# ---------------------------------------------------------------------------+# Toolchain check+# ---------------------------------------------------------------------------+command -v python3 &>/dev/null || halt "python3 is required."+command -v node &>/dev/null || halt "Node.js is required."++# ---------------------------------------------------------------------------+# Stage a clean copy of the repository+# ---------------------------------------------------------------------------+step "Preparing the build directory..."+rm -rf "$BUILD_DIR"+mkdir -p "$BUILD_DIR"++step "Copying the source tree..."+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+rsync -a --exclude=.git --exclude=node_modules --exclude=venv --exclude=__pycache__ \+ --exclude=.pytest_cache --exclude=instance --exclude=dist --exclude=backups \+ "$REPO_ROOT/" "$BUILD_DIR/"++# ---------------------------------------------------------------------------+# Bake the Python virtual environment+# ---------------------------------------------------------------------------+step "Creating the Python virtual environment..."+python3 -m venv "$BUILD_DIR/venv"+source "$BUILD_DIR/venv/bin/activate"+pip install --upgrade pip --quiet+pip install -r "$BUILD_DIR/backend/requirements.txt" --quiet+pip install gunicorn gevent gevent-websocket --quiet++# ---------------------------------------------------------------------------+# Build the frontend bundle+# ---------------------------------------------------------------------------+step "Building the frontend..."+cd "$BUILD_DIR/frontend"+npm ci --prefer-offline 2>&1 | tail -5+NODE_OPTIONS="--max-old-space-size=1024" npm run build 2>&1 | tail -10++# ---------------------------------------------------------------------------+# Strip development artifacts from the staged tree+# ---------------------------------------------------------------------------+step "Cleaning release artifacts..."+rm -rf "$BUILD_DIR/frontend/node_modules"+find "$BUILD_DIR" -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true+find "$BUILD_DIR" -type d -name .pytest_cache -exec rm -rf {} + 2>/dev/null || true+find "$BUILD_DIR" -type f -name '*.pyc' -delete 2>/dev/null || true++# Runtime directory the app expects to exist.+mkdir -p "$BUILD_DIR/backend/instance"++# ---------------------------------------------------------------------------+# Pack the tarball with an /opt/serverkit prefix+# ---------------------------------------------------------------------------+step "Creating the tarball..."+# Land the tarball at the repo root (matches .gitignore's /serverkit-*.tar.gz).+# Note: REPO_ROOT is captured up-front and stays valid after BUILD_DIR is moved.+DEST_DIR="$REPO_ROOT"+PACK_DIR="/tmp/serverkit-tarball-$$"+mkdir -p "$PACK_DIR/opt"+mv "$BUILD_DIR" "$PACK_DIR/opt/serverkit"++cd "$PACK_DIR/opt"+tar czf "${DEST_DIR}/${OUTPUT}" serverkit++cd "$DEST_DIR"+rm -rf "$PACK_DIR"++good "Release built: ${OUTPUT}"+ls -lh "${OUTPUT}"++printf '\n'+printf 'Upload this file to GitHub Releases: %s\n' "$OUTPUT"+printf 'Install with:\n'+printf ' curl -fsSL https://serverkit.ai/install.sh | INSTALL_FROM_RELEASE=1 bash\n\n'diff --git a/scripts/install.sh b/scripts/install.shindex 80389efb..4ce347d5 100644--- a/scripts/install.sh+++ b/scripts/install.sh@@ -15,12 +15,20 @@set -e-# Colors for output-RED='\033[0;31m'-GREEN='\033[0;32m'-YELLOW='\033[1;33m'-BLUE='\033[0;34m'-NC='\033[0m' # No Color+# Palette (truecolor violet gradient)+if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != "dumb" ]; then+ NC=$'\033[0m'; BOLD=$'\033[1m'+ fg() { printf '\033[38;2;%s;%s;%sm' "$1" "$2" "$3"; }+else+ NC=''; BOLD=''+ fg() { :; }+fi++V1="$(fg 196 181 253)"; V2="$(fg 167 139 250)"; V3="$(fg 139 92 246)"+V4="$(fg 124 58 237)"; V5="$(fg 109 40 217)"+WHITE="$(fg 237 233 254)"; MUTED="$(fg 165 160 190)"; FAINT="$(fg 113 108 140)"+GREEN="$(fg 52 211 153)"; RED="$(fg 248 113 113)"; YELLOW="$(fg 250 204 21)"+CYAN="$(fg 103 232 249)"# ConfigurationINSTALL_DIR="/usr/local/bin"@@ -37,27 +45,27 @@ SERVER_NAME=""VERSION="latest"print_banner() {- echo -e "${BLUE}"- echo "╔═══════════════════════════════════════════════════════════╗"- echo "║ ServerKit Agent Installer ║"- echo "╚═══════════════════════════════════════════════════════════╝"- echo -e "${NC}"+ echo+ printf " ${V1}${BOLD}╔═╗┌─┐┌─┐┌┬┐┌─┐┬┌─┐${NC}\n"+ printf " ${V2}${BOLD}╚═╗│ ││ │ ├┤ │├┤ ${NC} ${WHITE}${BOLD}ServerKit Agent${NC}\n"+ printf " ${V3}${BOLD}╚═╝└─┘└─┘ ┴ └─┘┴└──┘${NC} ${FAINT}v%s${NC}\n" "$VERSION"+ echo}log_info() {- echo -e "${BLUE}[INFO]${NC} $1"+ echo -e " ${CYAN}›${NC} $1"}log_success() {- echo -e "${GREEN}[SUCCESS]${NC} $1"+ echo -e " ${GREEN}●${NC} $1"}log_warn() {- echo -e "${YELLOW}[WARN]${NC} $1"+ echo -e " ${YELLOW}▲${NC} $1"}log_error() {- echo -e "${RED}[ERROR]${NC} $1"+ echo -e " ${RED}■${NC} $1"exit 1}@@ -283,6 +291,17 @@ ProtectSystem=strictProtectHome=trueReadWritePaths=${CONFIG_DIR} ${LOG_DIR}PrivateTmp=true+ProtectKernelLogs=yes+ProtectKernelModules=yes+ProtectKernelTunables=yes+ProtectControlGroups=yes+ProtectClock=yes+ProtectHostname=yes+RestrictRealtime=yes+RestrictSUIDSGID=yes+LockPersonality=yes+MemoryMax=512M+LimitNOFILE=65535# EnvironmentEnvironment=HOME=/nonexistentdiff --git a/scripts/update.sh b/scripts/update.shnew file mode 100644index 00000000..53b3dc70--- /dev/null+++ b/scripts/update.sh@@ -0,0 +1,341 @@+#!/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.+#+# 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+#+set -euo pipefail++# ---------------------------------------------------------------------------+# Terminal styling (violet ServerKit identity, degrades to plain text)+# ---------------------------------------------------------------------------+if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != "dumb" ]; then+ ESC=$'\033'+ RST="${ESC}[0m"; BLD="${ESC}[1m"+ paint() { printf '%s[38;2;%d;%d;%dm' "$ESC" "$1" "$2" "$3"; }+else+ RST=''; BLD=''+ paint() { :; }+fi++V3="$(paint 139 92 246)"; V4="$(paint 124 58 237)"+PAPER="$(paint 237 233 254)"; FOG="$(paint 113 108 140)"+HUE_OK="$(paint 52 211 153)"; HUE_WARN="$(paint 250 204 21)"+HUE_ERR="$(paint 248 113 113)"; HUE_LINK="$(paint 103 232 249)"++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"; }++STARTED_AT=0+PHASE_N=0+clock() {+ [ "$STARTED_AT" -gt 0 ] || { printf ''; return; }+ local secs=$(( $(date +%s) - STARTED_AT ))+ printf '%dm %02ds' "$((secs / 60))" "$((secs % 60))"+}+phase() {+ PHASE_N=$((PHASE_N + 1))+ printf '\n %s%s%02d%s %s%s%s %s%s%s\n' \+ "$BLD" "$V3" "$PHASE_N" "$RST" "$BLD" "$1" "$RST" "$FOG" "$(clock)" "$RST"+ printf ' %s%s%s\n\n' "$V4" "──────────────────────────────────────" "$RST"+}++# ---------------------------------------------------------------------------+# Settings+# ---------------------------------------------------------------------------+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"++# ---------------------------------------------------------------------------+# Sanity checks+# ---------------------------------------------------------------------------+[ "$EUID" -eq 0 ] || halt "Run as root."+[ -d "$INSTALL_DIR" ] || halt "ServerKit is not installed at $INSTALL_DIR"++# ---------------------------------------------------------------------------+# Pick install mode: release tarball vs. source tree+# ---------------------------------------------------------------------------+if [ "$INSTALL_FROM_RELEASE" != "1" ] && [ ! -d "$INSTALL_DIR/backend/src" ]; then+ step "No source tree found — switching to release download."+ INSTALL_FROM_RELEASE=1+fi+[ "$BUILD_FROM_SOURCE" = "1" ] && INSTALL_FROM_RELEASE=0++# ---------------------------------------------------------------------------+# 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+ fi+ rm -f "$tmp"+ 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"+ fi+}+backfill_encryption_key++# ---------------------------------------------------------------------------+# Header+# ---------------------------------------------------------------------------+printf '\n %s%sServerKit Updater%s\n' "$BLD" "$PAPER" "$RST"+STARTED_AT=$(date +%s)++CURRENT_VERSION=$(cat "$INSTALL_DIR/VERSION" 2>/dev/null | tr -d '\n\r ' || echo "unknown")+step "Current version: $CURRENT_VERSION"++# ---------------------------------------------------------------------------+# Pull latest source (source-mode only)+# ---------------------------------------------------------------------------+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"+ else+ warn "Repo sync failed — keeping the existing source."+ fi+fi++# ---------------------------------------------------------------------------+# Back up database + install tree+# ---------------------------------------------------------------------------+phase "Database Backup"+mkdir -p "$BACKUP_DIR"++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"+ else+ halt "Database backup failed — aborting upgrade."+ 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."++# ---------------------------------------------------------------------------+# Stop the stack+# ---------------------------------------------------------------------------+phase "Stopping Services"+systemctl stop "$BACKEND_SERVICE" 2>/dev/null || true+systemctl stop nginx 2>/dev/null || true++# ---------------------------------------------------------------------------+# Deploy: download a release, or rebuild from source+# ---------------------------------------------------------------------------+if [ "$INSTALL_FROM_RELEASE" = "1" ]; then+ phase "Downloading Release"++ case "$(uname -m)" in+ x86_64) DL_ARCH="amd64" ;;+ aarch64|arm64) DL_ARCH="arm64" ;;+ *) halt "Unsupported architecture: $(uname -m)" ;;+ esac++ 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"++ # Carry the live .env and database across.+ cp "$INSTALL_DIR/.env" "$STAGE/serverkit/.env" 2>/dev/null || true+ cp "$INSTALL_DIR/backend/instance/serverkit.db" \+ "$STAGE/serverkit/backend/instance/serverkit.db" 2>/dev/null || true++ mv "$INSTALL_DIR" "$INSTALL_DIR.old"+ mv "$STAGE/serverkit" "$INSTALL_DIR"+ rm -rf "$STAGE"+ good "Release deployed."+else+ phase "Updating Source"+ cd "$INSTALL_DIR"++ chmod +x "$INSTALL_DIR/serverkit"+ chmod +x "$INSTALL_DIR/scripts/"*.sh 2>/dev/null || true++ step "Updating Python dependencies..."+ source "$VENV_DIR/bin/activate"+ pip install -r "$INSTALL_DIR/backend/requirements.txt" --quiet++ 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++# ---------------------------------------------------------------------------+# Refresh nginx + systemd from the new tree+# ---------------------------------------------------------------------------+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++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"+ fi+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."++# ---------------------------------------------------------------------------+# Bring the stack back up+# ---------------------------------------------------------------------------+phase "Starting Services"+systemctl start "$BACKEND_SERVICE"+cd "$INSTALL_DIR"+docker compose up -d 2>&1 | tail -5+systemctl start nginx+good "Services started."++# ---------------------------------------------------------------------------+# Health check; restore the previous tree on failure+# ---------------------------------------------------------------------------+phase "Health Check"++roll_back() {+ warn "Health check failed — rolling back..."+ systemctl stop "$BACKEND_SERVICE" 2>/dev/null || true+ systemctl 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+ systemctl daemon-reload+ systemctl start "$BACKEND_SERVICE" 2>/dev/null || true+ systemctl start nginx 2>/dev/null || true+ halt "Update rolled back. 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+ fi+ 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++# ---------------------------------------------------------------------------+# Cleanup + telemetry+# ---------------------------------------------------------------------------+phase "Cleanup"++[ -d "$INSTALL_DIR.old" ] && rm -rf "$INSTALL_DIR.old"++# 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++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+# ---------------------------------------------------------------------------+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 ' %sCLI%s serverkit status\n\n' "$BLD" "$RST"diff --git a/serverkit b/serverkitindex 8fa0864e..00453020 100644--- a/serverkit+++ b/serverkit@@ -154,6 +154,7 @@ cmd_help() {echo " logs [service] View logs (backend, frontend, or all)"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 " branch Show current branch"echo " uninstall Uninstall ServerKit"@@ -357,6 +358,8 @@ cmd_branch() {cmd_update() {local force_update=falselocal target_branch=""+ local use_release=false+ local release_version=""# Parse argumentswhile [[ $# -gt 0 ]]; do@@ -369,6 +372,15 @@ cmd_update() {target_branch="$2"shift 2;;+ --release|-r)+ use_release=true+ if [[ -n "${2:-}" ]] && [[ ! "$2" =~ ^- ]]; then+ release_version="$2"+ shift 2+ else+ shift+ fi+ ;;*)shift;;@@ -380,6 +392,41 @@ 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