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(install): Phase 1 hardening — firewall automation, py3.11/3.12, unified uninstall
Juan Denis754bfb4a6775
diff --git a/install.sh b/install.shindex 926c3729..57173ac7 100644--- a/install.sh+++ b/install.sh@@ -57,6 +57,23 @@ SAFE_MODE=falseSSL_MODE="insecure"FIRST_SLOT="$DIR_A"+# Resolve where this script (and thus the bundled scripts/lib helpers) lives so+# shared libraries load whether we run from a clone, a release tree, or piped+# through `curl | bash`. The clone-relative path is tried first; once the source+# is on disk under $INSTALL_DIR that path works too.+SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd || true)"+load_serverkit_lib() {+ local name="$1" d+ for d in "$SELF_DIR/scripts/lib" "$INSTALL_DIR/scripts/lib"; do+ if [ -n "$d" ] && [ -f "$d/$name" ]; then+ # shellcheck source=/dev/null+ source "$d/$name"+ return 0+ fi+ done+ return 1+}+# ---------------------------------------------------------------------------# Terminal styling#@@ -270,16 +287,23 @@ ver_in_range() {}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+ # Prefer an explicit minor version, newest first, then bare python3. This+ # mirrors scripts/update.sh so a box that has python3.11 (Debian 12) but a+ # too-new/too-old default python3 is still recognized. Sets PYTHON_BIN and+ # returns 0 on success; returns 1 (without aborting) when nothing fits.+ local c v+ for c in python3.12 python3.11 python3; do+ if command -v "$c" &>/dev/null; then+ v=$("$c" -c 'import sys;print(".".join(map(str,sys.version_info[:2])))' 2>/dev/null || true)+ if [ -n "$v" ] && ver_in_range "$v"; then+ PYTHON_BIN="$c"+ good "Using $c (Python $v)"+ return 0+ fifi- fi- warn "System Python is outside the supported $PYTHON_MIN–$PYTHON_MAX range."+ done+ PYTHON_BIN=""+ return 1}build_python_from_source() {@@ -296,37 +320,58 @@ build_python_from_source() {provision_python() {phase "Installing Python"- locate_python- [ -n "$PYTHON_BIN" ] && return+ # Already have a supported interpreter? Nothing to do.+ if locate_python; then+ return+ fi++ warn "No supported Python ($PYTHON_MIN–$PYTHON_MAX) found — installing one."- step "Installing Python 3.12..."+ # Prefer the distro's own package over a source compile. Debian 12 ships+ # python3.11; Ubuntu 24.04 ships python3.12 (older Ubuntu falls back to the+ # deadsnakes PPA); Fedora/RHEL provide 3.12 or 3.11 in their repos. A slow,+ # fragile source build is now strictly the last resort.if [ "$OS_FAMILY" = "debian" ]; then- if [ "$ID" = "ubuntu" ]; then- pkg_add software-properties-common- add-apt-repository -y ppa:deadsnakes/ppa- refresh_pkg_index- pkg_add python3.12 python3.12-venv python3.12-dev+ if [ "${ID:-}" = "ubuntu" ]; then+ if ! pkg_add python3.12 python3.12-venv python3.12-dev; then+ step "Adding deadsnakes PPA for Python 3.12..."+ pkg_add software-properties-common+ add-apt-repository -y ppa:deadsnakes/ppa+ refresh_pkg_index+ pkg_add python3.12 python3.12-venv python3.12-dev+ fielse- 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 libffi-dev libssl-dev- build_python_from_source+ # Debian (and Debian-like): python3.11 lives in the main repo.+ refresh_pkg_index+ pkg_add python3.11 python3.11-venv python3.11-dev || \+ pkg_add python3.12 python3.12-venv python3.12-dev || truefi- 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- build_python_from_source- fi- PYTHON_BIN="python3.12"+ pkg_add python3.12 python3.12-devel || pkg_add python3.11 python3.11-devel || truefi+ # Did a distro package give us something usable?+ if locate_python; then+ good "Python ready: $PYTHON_BIN"+ return+ fi++ # Last resort: compile from source.+ warn "Distro packages did not provide a supported Python — building from source."+ if [ "$OS_FAMILY" = "debian" ]; then+ pkg_add wget zlib1g-dev libbz2-dev libreadline-dev \+ libsqlite3-dev libncurses5-dev libncursesw5-dev \+ xz-utils tk-dev liblzma-dev libffi-dev libssl-dev+ else+ pkg_add wget zlib-devel bzip2-devel readline-devel \+ sqlite-devel ncurses-devel xz-devel tk-devel libffi-devel+ fi+ build_python_from_source+ PYTHON_BIN="python3.12"+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."+ halt "Could not install a supported Python — install Python 3.11 or 3.12 by hand."+ good "Python installed ($PYTHON_BIN)."}# ---------------------------------------------------------------------------@@ -375,6 +420,17 @@ ensure_compose_plugin() {# ---------------------------------------------------------------------------# Node.js 20 (only needed for source builds — releases ship a built frontend)# ---------------------------------------------------------------------------+# Node 18+ is the floor for the Vite frontend build. Distro nodejs on every+# currently-supported target (Ubuntu 24.04, Debian 12, Fedora 40+) already meets+# it, so we install the distro package first and only pipe NodeSource into bash+# when the distro can't deliver a new-enough Node + npm.+node_major() { node --version 2>/dev/null | sed -E 's/^v([0-9]+).*/\1/'; }+node_ready() {+ command -v node &>/dev/null && command -v npm &>/dev/null || return 1+ local m; m="$(node_major)"+ [ -n "$m" ] && [ "$m" -ge 18 ] 2>/dev/null+}+provision_node() {phase "Node.js"@@ -383,18 +439,28 @@ provision_node() {returnfi- if command -v node &>/dev/null; then+ if node_ready; thengood "Node.js already present: $(node --version)"returnfi- step "Installing Node.js 20 LTS..."- if [ "$OS_FAMILY" = "debian" ]; then- curl -fsSL https://deb.nodesource.com/setup_20.x | bash - >/dev/null 2>&1- else- curl -fsSL https://rpm.nodesource.com/setup_20.x | bash - >/dev/null 2>&1+ step "Installing Node.js (distro repo first)..."+ # Debian/Ubuntu split npm into its own package; Fedora bundles it.+ pkg_add nodejs npm 2>/dev/null || pkg_add nodejs 2>/dev/null || true+ command -v npm &>/dev/null || pkg_add npm 2>/dev/null || true++ if ! node_ready; then+ warn "Distro Node.js is missing or older than 18 — falling back to NodeSource 20."+ if [ "$OS_FAMILY" = "debian" ]; then+ curl -fsSL https://deb.nodesource.com/setup_20.x | bash - >/dev/null 2>&1 || true+ else+ curl -fsSL https://rpm.nodesource.com/setup_20.x | bash - >/dev/null 2>&1 || true+ fi+ pkg_add nodejs || truefi- pkg_add nodejs++ node_ready || \+ halt "Node.js 18+ (with npm) is required but could not be installed. Install Node 20 LTS and re-run."good "Node.js $(node --version) installed."}@@ -586,7 +652,7 @@ write_config() {local secret_key jwt_secret encryption_keysecret_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())')+ encryption_key=$("${PYTHON_BIN:-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"@@ -673,6 +739,38 @@ build_frontend() {good "Frontend built."}+# ---------------------------------------------------------------------------+# Firewall: open 80/443 so the panel is reachable from the outside, and record+# exactly what we opened in /etc/serverkit/install-state.json so uninstall can+# undo only those rules. Fresh RHEL-family boxes run firewalld by default, which+# is the #1 reason an otherwise-good install looks "broken" (port 80 blocked).+# ---------------------------------------------------------------------------+configure_firewall() {+ phase "Firewall"++ if ! load_serverkit_lib firewall.sh; then+ warn "Firewall helper not found — open ports 80/443 manually if needed."+ return 0+ fi+ load_serverkit_lib state.sh || true++ local backend+ backend="$(firewall_detect)"+ if [ "$backend" = "none" ]; then+ warn "No active firewall detected — assuming ports 80/443 are already open."+ return 0+ fi++ step "Opening HTTP/HTTPS (80, 443) via $backend..."+ firewall_open "$backend" 80/tcp 443/tcp+ if [ "${FW_DRY_RUN:-0}" != "1" ] && command -v state_set >/dev/null 2>&1; then+ state_set firewall_backend "$backend"+ state_append firewall_ports 80/tcp+ state_append firewall_ports 443/tcp+ fi+ good "Firewall configured ($backend): 80/tcp and 443/tcp open."+}+# ---------------------------------------------------------------------------# nginx site + reverse-proxy wiring# ---------------------------------------------------------------------------@@ -1045,6 +1143,7 @@ main() {sync_templatesconfigure_nginx+ configure_firewallwrite_configinstall_service@@ -1058,4 +1157,9 @@ main() {print_outro}+# Sourcing this file (e.g. from scripts/test/test_install.sh) defines every+# function above for unit testing without running an install. Only a direct+# execution falls through to the run below.+[ "${BASH_SOURCE[0]}" = "${0}" ] || return 0+main "$@"diff --git a/scripts/lib/firewall.sh b/scripts/lib/firewall.shnew file mode 100644index 00000000..b5ddcc10--- /dev/null+++ b/scripts/lib/firewall.sh@@ -0,0 +1,139 @@+# shellcheck shell=bash+#+# scripts/lib/firewall.sh — sourceable firewall abstraction.+#+# Detects the active host firewall and opens/closes the ports ServerKit needs+# (80/443, optionally 5000). Fresh Rocky/Alma/RHEL/Fedora boxes ship firewalld+# active by default, which silently blocks 80/443 — making a perfectly good+# install look "broken" because the panel is unreachable. This helper fixes+# that automatically and, crucially, is reversible: callers persist exactly+# what was opened (see scripts/lib/state.sh) so uninstall can undo only those+# rules and never touch a user's own firewall config.+#+# Contract:+# firewall_detect → echoes: firewalld|ufw|nftables|iptables|none+# firewall_open <backend> <port...> → open ports (each "80/tcp")+# firewall_close <backend> <port...> → close the same ports+#+# Honors:+# FW_DRY_RUN=1 print intended commands instead of running them+# FIREWALL_BACKEND=... force the detected backend (used by unit tests)+#+# Everything is best-effort: a firewall we can't drive cleanly degrades to a+# warning rather than aborting the install.++# Run a privileged firewall command, or just print it under dry-run. Kept tiny+# so the dry-run output is exactly the command that would otherwise execute —+# which is what the installer unit tests assert against.+_fw_run() {+ if [ "${FW_DRY_RUN:-0}" = "1" ]; then+ printf ' [firewall] would run: %s\n' "$*"+ return 0+ fi+ # Discard the tool's own chatter ("success", rule-exists noise) here so+ # callers don't redirect — that redirection would also swallow the dry-run+ # line above, which the installer unit tests assert on.+ "$@" >/dev/null 2>&1+}++# Detect the active firewall. Order matters: a box can have several of these+# binaries installed but only one actually managing the input chain, so we pick+# the highest-level manager that reports itself active.+firewall_detect() {+ if [ -n "${FIREWALL_BACKEND:-}" ]; then+ printf '%s\n' "$FIREWALL_BACKEND"+ return 0+ fi+ if command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then+ printf 'firewalld\n'; return 0+ fi+ if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -qiE '^Status:[[:space:]]*active'; then+ printf 'ufw\n'; return 0+ fi+ if command -v nft >/dev/null 2>&1 && nft list ruleset >/dev/null 2>&1; then+ printf 'nftables\n'; return 0+ fi+ if command -v iptables >/dev/null 2>&1; then+ printf 'iptables\n'; return 0+ fi+ printf 'none\n'+}++# Split "80/tcp" into port + proto (proto defaults to tcp).+_fw_port() { printf '%s' "${1%%/*}"; }+_fw_proto() { case "$1" in */*) printf '%s' "${1##*/}" ;; *) printf 'tcp' ;; esac; }++firewall_open() {+ local backend="$1"; shift+ local spec port proto+ case "$backend" in+ firewalld)+ for spec in "$@"; do+ port="$(_fw_port "$spec")"; proto="$(_fw_proto "$spec")"+ _fw_run firewall-cmd --permanent "--add-port=${port}/${proto}" || true+ done+ _fw_run firewall-cmd --reload || true+ ;;+ ufw)+ for spec in "$@"; do+ port="$(_fw_port "$spec")"; proto="$(_fw_proto "$spec")"+ _fw_run ufw allow "${port}/${proto}" || true+ done+ ;;+ iptables)+ for spec in "$@"; do+ port="$(_fw_port "$spec")"; proto="$(_fw_proto "$spec")"+ # -C tests for an existing rule so we stay idempotent; -I only if absent.+ _fw_run iptables -C INPUT -p "$proto" --dport "$port" -j ACCEPT || \+ _fw_run iptables -I INPUT -p "$proto" --dport "$port" -j ACCEPT || true+ done+ ;;+ nftables)+ for spec in "$@"; do+ port="$(_fw_port "$spec")"; proto="$(_fw_proto "$spec")"+ # Best-effort: requires an inet filter/input chain to exist.+ _fw_run nft add rule inet filter input "$proto" dport "$port" accept || true+ done+ ;;+ none|*)+ return 0+ ;;+ esac+}++firewall_close() {+ local backend="$1"; shift+ local spec port proto+ case "$backend" in+ firewalld)+ for spec in "$@"; do+ port="$(_fw_port "$spec")"; proto="$(_fw_proto "$spec")"+ _fw_run firewall-cmd --permanent "--remove-port=${port}/${proto}" || true+ done+ _fw_run firewall-cmd --reload || true+ ;;+ ufw)+ for spec in "$@"; do+ port="$(_fw_port "$spec")"; proto="$(_fw_proto "$spec")"+ _fw_run ufw delete allow "${port}/${proto}" || true+ done+ ;;+ iptables)+ for spec in "$@"; do+ port="$(_fw_port "$spec")"; proto="$(_fw_proto "$spec")"+ _fw_run iptables -D INPUT -p "$proto" --dport "$port" -j ACCEPT || true+ done+ ;;+ nftables|none|*)+ # nftables rule deletion needs the rule handle; we can't reliably+ # find it after the fact, so leave it to the operator.+ return 0+ ;;+ esac+}++# Warn-and-document fallback text for when no firewall could be driven.+firewall_manual_hint() {+ local ports="$1"+ printf 'Open these ports manually so the panel is reachable: %s\n' "$ports"+}diff --git a/scripts/lib/state.sh b/scripts/lib/state.shnew file mode 100644index 00000000..f4d6cb06--- /dev/null+++ b/scripts/lib/state.sh@@ -0,0 +1,105 @@+# shellcheck shell=bash+#+# scripts/lib/state.sh — tiny install-state tracker.+#+# ServerKit makes a handful of global, host-wide changes during install+# (firewall ports, an apt lock-wait drop-in, an nginx TLS snippet). For uninstall+# to be reliable and for re-runs to be idempotent, we record exactly what we+# touched in /etc/serverkit/install-state.json and undo only those things on the+# way out — never a rule or file the operator added themselves (Goal G8).+#+# Backed by python3, which is a hard ServerKit dependency (the whole backend is+# Python), so it is present on any installed box. If python3 is somehow missing+# the helpers degrade to warn-and-no-op rather than aborting the caller.+#+# API:+# state_set <key> <value> set a scalar+# state_get <key> print a scalar ("" if absent)+# state_append <key> <value> append to an array (deduped)+# state_list <key> print array items, one per line+# state_unset <key> remove a key entirely+#+# Override the file location with SERVERKIT_STATE_FILE (used by tests).++SERVERKIT_STATE_FILE="${SERVERKIT_STATE_FILE:-/etc/serverkit/install-state.json}"++_state_have_py() { command -v python3 >/dev/null 2>&1; }++_state_py() {+ # Args: <action> <key> [value]+ SERVERKIT_STATE_FILE="$SERVERKIT_STATE_FILE" python3 - "$@" <<'PY'+import json, os, sys++path = os.environ["SERVERKIT_STATE_FILE"]+action = sys.argv[1] if len(sys.argv) > 1 else ""+key = sys.argv[2] if len(sys.argv) > 2 else ""+value = sys.argv[3] if len(sys.argv) > 3 else ""++try:+ with open(path) as fh:+ data = json.load(fh)+ if not isinstance(data, dict):+ data = {}+except (FileNotFoundError, ValueError):+ data = {}++def save():+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)+ tmp = path + ".tmp"+ with open(tmp, "w") as fh:+ json.dump(data, fh, indent=2, sort_keys=True)+ fh.write("\n")+ os.replace(tmp, path)++if action == "set":+ data[key] = value+ save()+elif action == "get":+ v = data.get(key, "")+ if v is not None:+ sys.stdout.write(str(v))+elif action == "append":+ arr = data.get(key)+ if not isinstance(arr, list):+ arr = []+ if value not in arr:+ arr.append(value)+ data[key] = arr+ save()+elif action == "list":+ arr = data.get(key)+ if isinstance(arr, list):+ for item in arr:+ sys.stdout.write(str(item) + "\n")+elif action == "unset":+ data.pop(key, None)+ save()+else:+ sys.exit(2)+PY+}++state_set() {+ _state_have_py || { printf ' [state] python3 unavailable — not recording %s\n' "$1" >&2; return 0; }+ _state_py set "$1" "$2"+}++state_get() {+ _state_have_py || return 0+ _state_py get "$1"+}++state_append() {+ _state_have_py || { printf ' [state] python3 unavailable — not recording %s\n' "$1" >&2; return 0; }+ _state_py append "$1" "$2"+}++state_list() {+ _state_have_py || return 0+ _state_py list "$1"+}++state_unset() {+ _state_have_py || return 0+ _state_py unset "$1"+}diff --git a/scripts/lib/uninstall.sh b/scripts/lib/uninstall.shnew file mode 100644index 00000000..48e3d013--- /dev/null+++ b/scripts/lib/uninstall.sh@@ -0,0 +1,205 @@+# shellcheck shell=bash+#+# scripts/lib/uninstall.sh — the one canonical uninstall routine.+#+# Both entry points (the standalone uninstall.sh and `serverkit uninstall`) used+# to carry their own copy of the teardown logic and had quietly drifted apart —+# `serverkit uninstall` ran `docker compose down -v` (destroying volumes) while+# uninstall.sh ran `down` (keeping them), so the same command name deleted your+# data in one path and not the other. This module is the single source of truth;+# the callers only handle their own banner + confirmation, then call+# serverkit_uninstall_core. It is non-interactive (testable) and parameterized+# entirely through environment variables.+#+# Inputs (all optional):+# SERVERKIT_DIR install dir (default /opt/serverkit)+# SERVERKIT_PURGE 1 → also remove Docker volumes, the SQLite DB, and all+# data dirs (/var/lib, /var/serverkit, backups, /etc)+# SERVERKIT_KEEP_DATA 1 → preserve /var/lib/serverkit, /etc/serverkit and+# /var/backups/serverkit (overrides the default+# config-dir removal). Ignored when PURGE=1.+# SERVERKIT_UNINSTALL_DRY_RUN 1 → print actions, change nothing.+#+# Data-handling matrix:+# default --keep-data --purge+# code (install dir + slots) remove remove remove+# systemd/nginx/apt/CLI/firewall remove remove remove+# logs (/var/log/serverkit) remove remove remove+# Docker volumes keep keep remove (-v)+# /etc/serverkit (config) remove keep remove+# /var/lib/serverkit keep keep remove+# /var/serverkit (apps) keep keep remove+# /var/backups/serverkit keep keep remove+# live SQLite DB backed up backed up remove+#+# "Default preserves data" is honored for both deployment shapes: all-Docker DBs+# live in a volume (kept without -v); hybrid DBs live in the install dir, so we+# snapshot the DB into /var/backups/serverkit before removing the tree.++# Self-contained logging (no dependency on the caller's color helpers).+_u_info() { printf ' \033[0;34m→\033[0m %s\n' "$1"; }+_u_ok() { printf ' \033[0;32m✓\033[0m %s\n' "$1"; }+_u_warn() { printf ' \033[1;33m!\033[0m %s\n' "$1"; }++_u_run() {+ if [ "${SERVERKIT_UNINSTALL_DRY_RUN:-0}" = "1" ]; then+ printf ' [uninstall] would run: %s\n' "$*"+ return 0+ fi+ "$@"+}++# Remove the firewall rules we (and only we) added, reading the record left in+# install-state.json. Must run BEFORE the config dir is deleted.+_u_firewall_cleanup() {+ local lib="$1/scripts/lib"+ [ -f "$lib/firewall.sh" ] || return 0+ [ -f "$lib/state.sh" ] || return 0+ # shellcheck source=/dev/null+ source "$lib/firewall.sh"+ # shellcheck source=/dev/null+ source "$lib/state.sh"+ command -v state_get >/dev/null 2>&1 || return 0++ local backend ports+ backend="$(state_get firewall_backend 2>/dev/null || true)"+ [ -n "$backend" ] || return 0+ ports="$(state_list firewall_ports 2>/dev/null | tr '\n' ' ')"+ [ -n "$ports" ] || return 0++ _u_info "Removing firewall rules we added ($backend): $ports"+ if [ "${SERVERKIT_UNINSTALL_DRY_RUN:-0}" = "1" ]; then+ FW_DRY_RUN=1 firewall_close "$backend" $ports+ else+ # shellcheck disable=SC2086+ firewall_close "$backend" $ports || true+ fi+}++serverkit_uninstall_core() {+ local install_dir="${SERVERKIT_DIR:-/opt/serverkit}"+ local purge="${SERVERKIT_PURGE:-0}"+ local keep_data="${SERVERKIT_KEEP_DATA:-0}"+ [ "$purge" = "1" ] && keep_data=0 # purge wins; keeping data makes no sense++ local data_dir="/var/lib/serverkit"+ local apps_dir="/var/serverkit"+ local config_dir="/etc/serverkit"+ local log_dir="/var/log/serverkit"+ local backup_dir="/var/backups/serverkit"++ # ---- Stop services -----------------------------------------------------+ _u_info "Stopping services..."+ _u_run systemctl stop serverkit 2>/dev/null || true+ _u_run systemctl disable serverkit 2>/dev/null || true+ _u_ok "Backend service stopped"++ # ---- Snapshot the live DB (unless purging) -----------------------------+ if [ "$purge" != "1" ]; then+ _u_snapshot_db "$install_dir" "$backup_dir"+ fi++ # ---- Containers --------------------------------------------------------+ if command -v docker >/dev/null 2>&1 && \+ { [ -e "$install_dir/docker-compose.yml" ] || [ -e "$install_dir/docker-compose.yaml" ]; }; then+ if [ "$purge" = "1" ]; then+ _u_info "Removing containers and volumes (--purge)..."+ _u_run docker compose --project-directory "$install_dir" down -v --remove-orphans 2>/dev/null || true+ else+ _u_info "Removing containers (volumes preserved)..."+ _u_run docker compose --project-directory "$install_dir" down --remove-orphans 2>/dev/null || true+ fi+ _u_ok "Containers removed"+ else+ _u_warn "Docker or compose file not found — skipping container cleanup"+ fi++ # ---- Firewall (read state before deleting the config dir) --------------+ _u_firewall_cleanup "$install_dir"++ # ---- systemd unit ------------------------------------------------------+ _u_info "Removing systemd service..."+ _u_run rm -f /etc/systemd/system/serverkit.service+ _u_run systemctl daemon-reload 2>/dev/null || true+ _u_ok "Systemd service removed"++ # ---- nginx ServerKit-owned configs -------------------------------------+ _u_info "Removing nginx configuration..."+ _u_run rm -f /etc/nginx/sites-enabled/serverkit.conf+ _u_run rm -f /etc/nginx/sites-available/serverkit.conf+ _u_run rm -f /etc/nginx/sites-available/serverkit-insecure.conf+ _u_run rm -f /etc/nginx/sites-available/example.conf.template+ _u_run rm -f /etc/nginx/conf.d/serverkit-tls.conf+ _u_run rm -rf /etc/nginx/serverkit-conf.d+ if systemctl is-active --quiet nginx 2>/dev/null; then+ _u_run systemctl reload nginx 2>/dev/null || true+ fi+ _u_ok "Nginx config removed"++ # ---- apt lock-wait drop-in (only the installer creates this) -----------+ _u_run rm -f /etc/apt/apt.conf.d/99-serverkit-lock-wait.conf++ # ---- CLI symlink -------------------------------------------------------+ _u_run rm -f /usr/local/bin/serverkit++ # ---- Code: install dir + blue/green slots + backup snapshot ------------+ _u_info "Removing installation files..."+ _u_run rm -rf "$install_dir"+ _u_run rm -rf "${install_dir}-a"+ _u_run rm -rf "${install_dir}-b"+ _u_run rm -rf "${install_dir}.backup"+ _u_ok "Installation directory removed"++ # ---- Logs (always transient) -------------------------------------------+ _u_run rm -rf "$log_dir"++ # ---- Data tiers --------------------------------------------------------+ if [ "$purge" = "1" ]; then+ _u_info "Purging data (--purge)..."+ _u_run rm -rf "$data_dir" "$apps_dir" "$backup_dir" "$config_dir"+ _u_ok "Data directories removed"+ else+ # Config dir holds install-state.json + ssl-mode + templates. Removed by+ # default, preserved with --keep-data.+ if [ "$keep_data" = "1" ]; then+ _u_info "Preserving data (--keep-data): $data_dir, $config_dir, $backup_dir"+ else+ _u_run rm -rf "$config_dir"+ _u_info "Preserved user data: $data_dir, $apps_dir, $backup_dir"+ fi+ fi++ # ---- Telemetry (best-effort) -------------------------------------------+ curl -s "https://serverkit.ai/track/uninstall" >/dev/null 2>&1 || true+}++# Snapshot the live SQLite DB into the (preserved) backup dir so a default+# uninstall never silently destroys the database with the install tree.+_u_snapshot_db() {+ local install_dir="$1" backup_dir="$2"+ local stamp db_src dest+ stamp="$(date +%Y%m%d-%H%M%S)"+ dest="$backup_dir/serverkit-pre-uninstall-$stamp.db"++ # Hybrid: DB sits in the install tree.+ db_src="$install_dir/backend/instance/serverkit.db"+ if [ -f "$db_src" ]; then+ _u_run mkdir -p "$backup_dir"+ if _u_run cp "$db_src" "$dest" 2>/dev/null; then+ _u_ok "Database snapshot saved to $dest"+ return 0+ fi+ fi++ # All-Docker: DB lives in the backend container's volume.+ if command -v docker >/dev/null 2>&1 && \+ docker ps -a --format '{{.Names}}' 2>/dev/null | grep -qx 'serverkit-backend'; then+ _u_run mkdir -p "$backup_dir"+ if _u_run docker cp serverkit-backend:/app/instance/serverkit.db "$dest" 2>/dev/null; then+ _u_ok "Database snapshot saved to $dest"+ return 0+ fi+ fi++ _u_warn "No live SQLite database found to snapshot — skipping"+}diff --git a/scripts/test/test_install.sh b/scripts/test/test_install.shnew file mode 100644index 00000000..28904836--- /dev/null+++ b/scripts/test/test_install.sh@@ -0,0 +1,211 @@+#!/usr/bin/env bash+#+# Unit tests for install.sh + scripts/lib/{firewall,state,uninstall}.sh —+# runs in seconds, no server, no install.+#+# install.sh is source-able: when sourced it defines every function and then+# returns *before* main() (the BASH_SOURCE guard). That lets us exercise the+# Python/Node detection, the firewall abstraction, the install-state tracker,+# and the canonical uninstall routine against throwaway fixtures and PATH stubs+# instead of a real distro and a real /etc.+#+# Each unit-under-test runs in a subshell that re-enables `set -Eeuo pipefail`,+# so an unguarded command silently aborting under set -e is caught here as a+# failed assertion rather than on someone's server.+#+# Run: bash scripts/test/test_install.sh+set -uo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+REPO_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"+INSTALL_SH="$REPO_DIR/install.sh"+LIB_DIR="$REPO_DIR/scripts/lib"++PASS=0+FAIL=0+SKIP=0+ok() { PASS=$((PASS + 1)); printf ' \033[32m✔\033[0m %s\n' "$1"; }+bad() { FAIL=$((FAIL + 1)); printf ' \033[31m✘\033[0m %s\n' "$1"; }+skip() { SKIP=$((SKIP + 1)); printf ' \033[33m∼\033[0m %s (skipped)\n' "$1"; }++WORK="$(mktemp -d)"+trap 'rm -rf "$WORK"' EXIT++# --------------------------------------------------------------------------+# PATH stubs.+# STUB_BIN — node/npm fakes, added on the global PATH only during T3.+# PY_STUB — fake python interpreters, applied ONLY inside T1's subshell so+# the real python3 stays available for the state.sh test (T6).+# Each python stub echoes a fixed "major.minor" when called with `-c`.+# --------------------------------------------------------------------------+STUB_BIN="$WORK/bin"+PY_STUB="$WORK/pybin"+mkdir -p "$STUB_BIN" "$PY_STUB"+mkpy() { # mkpy <name> <major.minor>+ {+ printf '#!/usr/bin/env bash\n'+ printf 'if [ "${1:-}" = "-c" ]; then printf "%s"; fi\n' "$2"+ } > "$PY_STUB/$1"+ chmod +x "$PY_STUB/$1"+}+# python3.12 reports an out-of-range 3.13 (rejected); python3.11 is in range;+# bare python3 is an old 3.10 (rejected). locate_python must therefore pick+# python3.11 — proving it no longer blindly trusts `python3`.+mkpy python3.12 3.13+mkpy python3.11 3.11+mkpy python3 3.10+export PATH="$STUB_BIN:$PATH"++# --------------------------------------------------------------------------+# Source install.sh (functions only). Point the install dir at the sandbox.+# --------------------------------------------------------------------------+export SERVERKIT_DIR="$WORK/opt/serverkit"+# shellcheck disable=SC1090+source "$INSTALL_SH"+set +e +u # hand control back to the harness; tests re-arm set -e per subshell++printf '\ninstall.sh + lib unit tests\n\n'++# --------------------------------------------------------------------------+# T1 — locate_python prefers a supported minor version over a too-old python3.+# --------------------------------------------------------------------------+res="$( set -Eeuo pipefail; PATH="$PY_STUB:$PATH"; locate_python >/dev/null 2>&1; printf '%s' "$PYTHON_BIN" )"+if [ "$res" = "python3.11" ]; then+ ok "locate_python picks python3.11 when python3 is 3.10 and python3.12 is out of range"+else+ bad "locate_python chose [$res], expected python3.11"+fi++# --------------------------------------------------------------------------+# T2 — ver_in_range gate (3.11/3.12 accepted, 3.10/3.13 rejected).+# --------------------------------------------------------------------------+if ( set -Eeuo pipefail; ver_in_range 3.11 ) && ( set -Eeuo pipefail; ver_in_range 3.12 ) && \+ ! ( set -Eeuo pipefail; ver_in_range 3.10 ) && ! ( set -Eeuo pipefail; ver_in_range 3.13 ); then+ ok "ver_in_range accepts 3.11/3.12 and rejects 3.10/3.13"+else+ bad "ver_in_range gate is wrong"+fi++# --------------------------------------------------------------------------+# T3 — node_ready requires node>=18 AND npm present.+# --------------------------------------------------------------------------+printf '#!/usr/bin/env bash\necho v18.19.0\n' > "$STUB_BIN/node"; chmod +x "$STUB_BIN/node"+printf '#!/usr/bin/env bash\nexit 0\n' > "$STUB_BIN/npm"; chmod +x "$STUB_BIN/npm"+if ( set -Eeuo pipefail; node_ready ); then+ ok "node_ready true for node v18 with npm present"+else+ bad "node_ready should be true for node v18 + npm"+fi+printf '#!/usr/bin/env bash\necho v16.20.0\n' > "$STUB_BIN/node"; chmod +x "$STUB_BIN/node"+if ( set -Eeuo pipefail; node_ready ); then+ bad "node_ready should be false for node v16"+else+ ok "node_ready false for node v16 (below the 18 floor)"+fi+rm -f "$STUB_BIN/node" "$STUB_BIN/npm"++# --------------------------------------------------------------------------+# T4 — configure_firewall dry-run prints the exact firewall commands and+# records nothing (FW_DRY_RUN suppresses state writes).+# --------------------------------------------------------------------------+state_file="$WORK/state-t4.json"+out="$(+ set -Eeuo pipefail+ export SERVERKIT_STATE_FILE="$state_file"+ FW_DRY_RUN=1 FIREWALL_BACKEND=firewalld configure_firewall 2>&1+)"+if printf '%s' "$out" | grep -q 'firewall-cmd --permanent --add-port=80/tcp' && \+ printf '%s' "$out" | grep -q 'firewall-cmd --permanent --add-port=443/tcp'; then+ ok "configure_firewall dry-run prints the expected firewalld commands"+else+ bad "configure_firewall dry-run did not print the expected commands"+fi+if [ ! -f "$state_file" ]; then+ ok "configure_firewall dry-run writes no install-state.json"+else+ bad "configure_firewall dry-run unexpectedly wrote state"+fi++# --------------------------------------------------------------------------+# T5 — firewall_detect honors the FIREWALL_BACKEND override.+# --------------------------------------------------------------------------+res="$( set -Eeuo pipefail; source "$LIB_DIR/firewall.sh"; FIREWALL_BACKEND=ufw firewall_detect )"+if [ "$res" = "ufw" ]; then+ ok "firewall_detect honors FIREWALL_BACKEND override"+else+ bad "firewall_detect ignored the override (got [$res])"+fi++# --------------------------------------------------------------------------+# T6 — state.sh roundtrip: set/get scalar, append dedup, list.+# --------------------------------------------------------------------------+if command -v python3 >/dev/null 2>&1; then+ res="$(+ set -Eeuo pipefail+ export SERVERKIT_STATE_FILE="$WORK/state-t6.json"+ source "$LIB_DIR/state.sh"+ state_set firewall_backend firewalld+ state_append firewall_ports 80/tcp+ state_append firewall_ports 443/tcp+ state_append firewall_ports 80/tcp # duplicate — must be ignored+ # tr -d '\r' normalizes the CRLF that Python's text-mode stdout emits on+ # Windows; on Linux there is nothing to strip.+ printf '%s|%s' "$(state_get firewall_backend | tr -d '\r')" \+ "$(state_list firewall_ports | tr -d '\r' | tr '\n' ',')"+ )"+ if [ "$res" = "firewalld|80/tcp,443/tcp," ]; then+ ok "state.sh set/get/append(dedup)/list roundtrip"+ else+ bad "state.sh roundtrip wrong: got [$res]"+ fi+else+ skip "state.sh roundtrip — python3 unavailable here"+fi++# --------------------------------------------------------------------------+# T7 — the canonical uninstall routine: default preserves data, --purge+# removes it, --keep-data preserves the config dir. All in dry-run.+# --------------------------------------------------------------------------+inst="$WORK/opt/serverkit"+mkdir -p "$inst/scripts/lib"+cp "$LIB_DIR/firewall.sh" "$LIB_DIR/state.sh" "$inst/scripts/lib/"+touch "$inst/docker-compose.yml"++uninstall_out() { # uninstall_out <extra-env>+ (+ set -Eeuo pipefail+ source "$LIB_DIR/uninstall.sh"+ export SERVERKIT_DIR="$inst" SERVERKIT_UNINSTALL_DRY_RUN=1+ eval "$1"+ serverkit_uninstall_core 2>&1+ )+}++def_out="$(uninstall_out '')"+if printf '%s' "$def_out" | grep -q 'down --remove-orphans' && \+ ! printf '%s' "$def_out" | grep -q 'down -v' && \+ ! printf '%s' "$def_out" | grep -q 'rm -rf /var/lib/serverkit'; then+ ok "uninstall default: compose down WITHOUT -v and keeps /var/lib/serverkit"+else+ bad "uninstall default behaved wrong (deleted data or used -v)"+fi++purge_out="$(uninstall_out 'export SERVERKIT_PURGE=1')"+if printf '%s' "$purge_out" | grep -q 'down -v' && \+ printf '%s' "$purge_out" | grep -q 'rm -rf /var/lib/serverkit'; then+ ok "uninstall --purge: compose down -v and removes data dirs"+else+ bad "uninstall --purge did not remove volumes/data"+fi++keep_out="$(uninstall_out 'export SERVERKIT_KEEP_DATA=1')"+if printf '%s' "$keep_out" | grep -q 'Preserving data' && \+ ! printf '%s' "$keep_out" | grep -q 'rm -rf /etc/serverkit'; then+ ok "uninstall --keep-data: preserves /etc/serverkit"+else+ bad "uninstall --keep-data removed the config dir"+fi++# --------------------------------------------------------------------------+printf '\n%d passed, %d failed, %d skipped\n\n' "$PASS" "$FAIL" "$SKIP"+[ "$FAIL" -eq 0 ]diff --git a/scripts/update.sh b/scripts/update.shindex ce6f991c..00af5606 100644--- a/scripts/update.sh+++ b/scripts/update.sh@@ -775,6 +775,43 @@ cleanup() {good "Cleanup complete"}+# ---------------------------------------------------------------------------+# Firewall — keep 80/443 open across updates.+# ---------------------------------------------------------------------------+# Idempotent and best-effort: a box installed before firewall automation existed+# gets its ports opened on the next update; an already-configured box is a no-op.+# Records what we opened in install-state.json so uninstall can undo it. Sources+# the helpers from the (now-current) install tree, which carries scripts/lib.+ensure_firewall() {+ local lib="$INSTALL_DIR/scripts/lib"+ [ -f "$lib/firewall.sh" ] || return 0+ # shellcheck source=/dev/null+ source "$lib/firewall.sh"+ if [ -f "$lib/state.sh" ]; then+ # shellcheck source=/dev/null+ source "$lib/state.sh"+ fi++ local backend+ backend="$(firewall_detect)"+ if [ "$backend" = "none" ]; then+ return 0+ fi++ if [ "$DRY_RUN" = "1" ]; then+ info "[dry-run] would ensure firewall ($backend) allows 80/tcp and 443/tcp"+ return 0+ fi++ firewall_open "$backend" 80/tcp 443/tcp || true+ if command -v state_set >/dev/null 2>&1; then+ state_set firewall_backend "$backend" || true+ state_append firewall_ports 80/tcp || true+ state_append firewall_ports 443/tcp || true+ fi+ good "Firewall ensured ($backend): 80/tcp and 443/tcp open"+}+# ---------------------------------------------------------------------------# All-Docker deployment (compose) detection + update path# ---------------------------------------------------------------------------@@ -996,6 +1033,9 @@ update_docker_compose() {# Healthy (or no healthcheck defined): the upgrade stuck, drop the snapshot.clear_docker_rollback+ # Keep the firewall in sync (idempotent, best-effort).+ ensure_firewall || true+local new_versionnew_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@@ -1126,6 +1166,9 @@ good "Services started"# Health check.health_check+# Keep the firewall in sync (idempotent, best-effort).+ensure_firewall || true+# Cleanup.cleanupdiff --git a/serverkit b/serverkitindex ac5949ad..7d883a78 100644--- a/serverkit+++ b/serverkit@@ -207,7 +207,11 @@ cmd_help() {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 " uninstall Uninstall ServerKit (preserves data by default)"+ echo " --purge / --delete-volumes also delete volumes, DB, data"+ echo " --keep-data also keep /etc/serverkit"+ echo " --yes skip the confirmation prompt"+ echo " --dry-run show actions without changing anything"echo ""echo "User Management:"echo " create-admin Create a new admin user"@@ -454,73 +458,64 @@ cmd_update() {cmd_uninstall() {check_root++ # Flags mirror uninstall.sh so both entry points accept the same options.+ local purge=0 keep_data=0 assume_yes=0 dry_run=0+ while [[ $# -gt 0 ]]; do+ case "$1" in+ --purge|--delete-volumes) purge=1; shift ;;+ --keep-data) keep_data=1; shift ;;+ --yes|-y) assume_yes=1; shift ;;+ --dry-run|-n) dry_run=1; shift ;;+ *) shift ;;+ esac+ done+print_headerecho ""- print_warning "This will remove ServerKit and all data!"- echo ""- echo "The following will be removed:"- echo " - ServerKit backend service (systemd)"- echo " - Frontend Docker container and images"- echo " - Installation directory ($INSTALL_DIR)"- echo " - Configuration (/etc/serverkit)"- echo " - App data (/var/serverkit)"- echo " - Logs (/var/log/serverkit)"- echo " - Nginx site configs for ServerKit"- echo " - CLI symlink (/usr/local/bin/serverkit)"+ if [ "$purge" = "1" ]; then+ print_warning "This will remove ServerKit AND delete all data (volumes, database, backups)."+ else+ print_warning "This will remove ServerKit. User data (volumes, /var/lib, backups) is preserved."+ echo " Use --purge to also delete data, or --keep-data to also keep /etc/serverkit."+ fi+ [ "$dry_run" = "1" ] && print_warning "DRY RUN — nothing will actually be changed."echo ""- read -p "Are you sure? (y/N) " -n 1 -r- echo- if [[ $REPLY =~ ^[Yy]$ ]]; then- # Track uninstall before removing files- UNINSTALL_VERSION=$(get_local_version)- curl -s "https://serverkit.ai/track/uninstall?v=${UNINSTALL_VERSION}" >/dev/null 2>&1 || true-- print_info "Stopping services..."- systemctl stop $BACKEND_SERVICE 2>/dev/null || true- systemctl disable $BACKEND_SERVICE 2>/dev/null || true-- cd "$INSTALL_DIR" 2>/dev/null && docker compose down -v 2>/dev/null || true-- # Move to safe directory before deleting install dir- cd /tmp 2>/dev/null || cd / || true-- print_info "Removing files..."- rm -f /etc/systemd/system/serverkit.service- rm -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/serverkit- rm -rf /var/lib/serverkit-- # Remove ServerKit config and app data- rm -rf /etc/serverkit- rm -rf /var/serverkit-- # Remove nginx site configs installed by ServerKit- print_info "Removing nginx configs..."- rm -f /etc/nginx/sites-enabled/serverkit.conf- rm -f /etc/nginx/sites-available/serverkit.conf- rm -f /etc/nginx/sites-available/example.conf.template- # Reload nginx if it's still running (don't stop it — user may use it for other sites)- if systemctl is-active --quiet nginx 2>/dev/null; then- systemctl reload nginx 2>/dev/null || true+ if [ "$assume_yes" != "1" ]; then+ read -p "Are you sure? (y/N) " -n 1 -r+ echo+ if [[ ! $REPLY =~ ^[Yy]$ ]]; then+ print_warning "Uninstall cancelled"+ return 0fi+ fi- systemctl daemon-reload-- print_success "ServerKit uninstalled"- echo ""- echo "Note: System packages (Docker, Node.js, nginx, Python) were NOT removed."- echo "Remove them manually if no longer needed."- echo ""- echo "To reinstall, run:"- echo " cd ~ && curl -fsSL https://serverkit.ai/install.sh | sudo bash"+ local lib="$INSTALL_DIR/scripts/lib/uninstall.sh"+ if [ ! -f "$lib" ]; then+ print_error "Canonical uninstall routine not found at $lib"+ exit 1fi++ # Source the shared routine into memory *before* it starts deleting the+ # install tree (which is where the file lives), then step out of that tree.+ # shellcheck source=/dev/null+ source "$lib"+ cd /tmp 2>/dev/null || cd / || true++ export SERVERKIT_DIR="$INSTALL_DIR"+ export SERVERKIT_PURGE="$purge"+ export SERVERKIT_KEEP_DATA="$keep_data"+ export SERVERKIT_UNINSTALL_DRY_RUN="$dry_run"+ serverkit_uninstall_core++ print_success "ServerKit uninstalled"+ echo ""+ echo "Note: System packages (Docker, Node.js, nginx, Python) were NOT removed."+ echo "Remove them manually if no longer needed."+ echo ""+ echo "To reinstall, run:"+ echo " cd ~ && curl -fsSL https://serverkit.ai/install.sh | sudo bash"}cmd_create_admin() {@@ -1259,7 +1254,8 @@ case "${1:-help}" incmd_check_update;;uninstall)- cmd_uninstall+ shift+ cmd_uninstall "$@";;create-admin)cmd_create_admindiff --git a/uninstall.sh b/uninstall.shindex 1bb9104c..5fcdeea9 100644--- a/uninstall.sh+++ b/uninstall.sh@@ -3,27 +3,73 @@ set -Eeuo pipefail######################################### ServerKit Uninstaller-########################################--INSTALL_DIR="/opt/serverkit"-DATA_DIR="/var/lib/serverkit"-LOG_DIR="/var/log/serverkit"+#+# Thin wrapper around the canonical teardown routine in+# scripts/lib/uninstall.sh — the same routine `serverkit uninstall` runs, so+# both entry points behave identically (they used to diverge on volume+# deletion).+#+# Usage:+# sudo ./uninstall.sh # remove ServerKit, preserve user data+# sudo ./uninstall.sh --purge # also delete Docker volumes, DB, data+# sudo ./uninstall.sh --keep-data # also preserve /etc + /var/lib + backups+# sudo ./uninstall.sh --yes # skip the confirmation prompt+# sudo ./uninstall.sh --dry-run # show what would happen, change nothing+#+# Honors SERVERKIT_DIR for non-default install locations.+########################################++INSTALL_DIR="${SERVERKIT_DIR:-/opt/serverkit}"LOG_FILE="/var/log/serverkit-uninstall.log"+PURGE=0+KEEP_DATA=0+ASSUME_YES=0+DRY_RUN=0++usage() {+ cat <<EOF+ServerKit uninstaller++Usage: uninstall.sh [OPTIONS]++Options:+ --purge, --delete-volumes Also remove Docker volumes, the SQLite database,+ and all data dirs (/var/lib, /var/serverkit, backups)+ --keep-data Preserve /var/lib/serverkit, /etc/serverkit and+ /var/backups/serverkit+ --yes, -y Do not prompt for confirmation+ --dry-run, -n Show what would be done without changing anything+ --help, -h Show this help++Environment:+ SERVERKIT_DIR Install directory (default: /opt/serverkit)+EOF+}++while [[ $# -gt 0 ]]; do+ case "$1" in+ --purge|--delete-volumes) PURGE=1; shift ;;+ --keep-data) KEEP_DATA=1; shift ;;+ --yes|-y) ASSUME_YES=1; shift ;;+ --dry-run|-n) DRY_RUN=1; shift ;;+ --help|-h) usage; exit 0 ;;+ *) echo "Unknown option: $1" >&2; usage; exit 1 ;;+ esac+done+mkdir -p /var/logexec > >(tee -a "$LOG_FILE") 2>&1########################################-# Colors+# Colors / masthead########################################-RED='\033[0;31m'GREEN='\033[0;32m'+RED='\033[0;31m'YELLOW='\033[1;33m'-BLUE='\033[0;34m'NC='\033[0m'-# Truecolor ServerKit identity (degrades to plain text when not supported)if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != "dumb" ]; thenESC=$'\033'RST_TC="${ESC}[0m"; BLD_TC="${ESC}[1m"@@ -33,14 +79,13 @@ elsepaint() { :; }fi-V1="$(paint 196 181 253)"; V2="$(paint 167 139 250)"; V3="$(paint 139 92 246)"+V2="$(paint 167 139 250)"; V3="$(paint 139 92 246)"V4="$(paint 124 58 237)"; V5="$(paint 109 40 217)"PAPER_TC="$(paint 237 233 254)"; ASH_TC="$(paint 165 160 190)"; FOG_TC="$(paint 113 108 140)"-HUE_OK_TC="$(paint 52 211 153)"; HUE_WARN_TC="$(paint 250 204 21)"; HUE_ERR_TC="$(paint 248 113 113)"; HUE_LINK_TC="$(paint 103 232 249)"+HUE_WARN_TC="$(paint 250 204 21)"-########################################-# UI helpers-########################################+print_error() { echo -e "${RED}✗ $1${NC}"; }+print_warning() { echo -e "${YELLOW}! $1${NC}"; }print_header() {local ver="unknown"@@ -58,11 +103,6 @@ print_header() {printf '\n'}-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}"; }-######################################### Root check########################################@@ -75,114 +115,57 @@ fiprint_header########################################-# Confirm uninstall+# Locate and source the canonical routine########################################-echo-read -p "Remove ServerKit completely? (y/N): " confirm--if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then- print_warning "Uninstall cancelled"- exit 0+SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd || true)"+UNINSTALL_LIB=""+for d in "$SELF_DIR/scripts/lib" "$INSTALL_DIR/scripts/lib"; do+ if [ -f "$d/uninstall.sh" ]; then+ UNINSTALL_LIB="$d/uninstall.sh"+ break+ fi+done+if [ -z "$UNINSTALL_LIB" ]; then+ print_error "Cannot find scripts/lib/uninstall.sh — is ServerKit installed at $INSTALL_DIR?"+ exit 1fi########################################-# Stop services-########################################--print_info "Stopping ServerKit service"--systemctl stop serverkit 2>/dev/null || true-systemctl disable serverkit 2>/dev/null || true--print_success "Backend service stopped"--########################################-# Stop containers+# Confirm########################################-print_info "Stopping Docker containers"--if command -v docker &>/dev/null && [ -d "$INSTALL_DIR" ]; then- docker compose --project-directory "$INSTALL_DIR" down --remove-orphans 2>/dev/null || true+echo+if [ "$PURGE" = "1" ]; then+ print_warning "This will remove ServerKit AND delete all data (volumes, database, backups)."else- print_warning "Docker or install directory not found, skipping container cleanup"+ print_warning "This will remove ServerKit. User data (volumes, /var/lib, backups) is preserved."+ echo " Use --purge to also delete data, or --keep-data to also keep /etc/serverkit."fi+[ "$DRY_RUN" = "1" ] && print_warning "DRY RUN — nothing will actually be changed."+echo-print_success "Containers removed"--########################################-# Remove systemd service-########################################--print_info "Removing systemd service"--rm -f /etc/systemd/system/serverkit.service--systemctl daemon-reload--print_success "Systemd service removed"--########################################-# Remove nginx config-########################################--print_info "Removing nginx configuration"--rm -f /etc/nginx/sites-enabled/serverkit.conf 2>/dev/null || true-rm -f /etc/nginx/sites-available/serverkit.conf 2>/dev/null || true--systemctl reload nginx 2>/dev/null || true--print_success "Nginx config removed"--########################################-# Remove files-########################################--print_info "Removing installation files"--rm -rf "$INSTALL_DIR"--print_success "Installation directory removed"--########################################-# Remove data-########################################--print_info "Removing data directory"--rm -rf "$DATA_DIR"-rm -rf /etc/serverkit-rm -rf /var/serverkit--print_success "Data directories removed"--########################################-# Remove logs-########################################--print_info "Removing logs"--rm -rf "$LOG_DIR"--print_success "Log directory removed"+if [ "$ASSUME_YES" != "1" ]; then+ read -r -p "Remove ServerKit$([ "$PURGE" = "1" ] && echo " and all data")? (y/N): " confirm+ if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then+ print_warning "Uninstall cancelled"+ exit 0+ fi+fi########################################-# Remove CLI+# Run the canonical teardown########################################-print_info "Removing CLI command"--rm -f /usr/local/bin/serverkit+# shellcheck source=scripts/lib/uninstall.sh+source "$UNINSTALL_LIB"-print_success "CLI removed"+export SERVERKIT_DIR="$INSTALL_DIR"+export SERVERKIT_PURGE="$PURGE"+export SERVERKIT_KEEP_DATA="$KEEP_DATA"+export SERVERKIT_UNINSTALL_DRY_RUN="$DRY_RUN"-########################################-# Track uninstall-########################################--curl -s "https://serverkit.ai/track/uninstall" >/dev/null 2>&1 || true+serverkit_uninstall_core######################################### Finish@@ -192,8 +175,7 @@ echoecho -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"echo -e "${GREEN} ServerKit removed successfully${NC}"echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"-echo-echo "Uninstall log:"-echo "$LOG_FILE"+echo "System packages (Docker, Node.js, nginx, Python) were NOT removed."+echo "Uninstall log: $LOG_FILE"echo