install.sh 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. #!/bin/sh
  2. # =============================================================================
  3. # NetPulse — one-liner installer (Linux server)
  4. #
  5. # Read-only PWA dashboard for monitoring OpenWrt/GL.iNet home networks.
  6. # Installs the single static Go binary (frontend embedded) as a sandboxed
  7. # systemd service.
  8. #
  9. # Usage:
  10. # curl -fsSL https://raw.githubusercontent.com/gnacho/netpulse/main/install.sh | sh
  11. # sh install.sh --version=1.0.0 --unattended
  12. # sh install.sh --dry-run # describe every step, touches nothing
  13. # sh install.sh --uninstall # keeps /var/lib/netpulse (data + .env)
  14. # sh install.sh --uninstall --purge
  15. #
  16. # Requirements: Linux with systemd (Debian/Ubuntu/Fedora/Arch/...),
  17. # amd64 / arm64 / armv7. Verifies sha256 of every download (checksums.txt).
  18. #
  19. # Layout (capistrano-less: single binary + state dir):
  20. # /usr/local/bin/netpulse binary
  21. # /var/lib/netpulse working dir: .env, data/ (SQLite), .ssh/
  22. # =============================================================================
  23. set -eu
  24. APP_NAME="netpulse"
  25. GH_REPO="gnacho/netpulse"
  26. BIN_NAME="netpulse"
  27. DEFAULT_PORT="3000"
  28. INSTALL_DIR="/usr/local/bin"
  29. STATE_DIR="/var/lib/$APP_NAME"
  30. SERVICE_NAME="$APP_NAME"
  31. # Versión de ESTE instalador (bumpear en cada release junto a httpapi.Version,
  32. # para poder saber qué install.sh se está ejecutando; ver CHANGELOG).
  33. INSTALLER_VERSION="2.28.11"
  34. NETPULSE_VERSION=""; UNATTENDED=0; DRY_RUN=0; UNINSTALL=0; PURGE=0; DEMO=0
  35. # ---------------------------------------------------------------- logging ---
  36. if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
  37. C_G=$(printf '\033[32m'); C_R=$(printf '\033[31m'); C_Y=$(printf '\033[33m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
  38. else C_G=""; C_R=""; C_Y=""; C_B=""; C_0=""; fi
  39. info() { printf '%s--%s %s\n' "$C_B" "$C_0" "$*"; }
  40. ok() { printf '%s✓%s %s\n' "$C_G" "$C_0" "$*"; }
  41. warn() { printf '%s!%s %s\n' "$C_Y" "$C_0" "$*" >&2; }
  42. err() { printf '%s✗ %s%s\n' "$C_R" "$*" "$C_0" >&2; }
  43. fatal() { _c=$1; shift; err "$*"; exit "$_c"; }
  44. run() { if [ "$DRY_RUN" -eq 1 ]; then info "[dry-run] $*"; else "$@"; fi; }
  45. usage() {
  46. cat <<EOF
  47. NetPulse — installer (network monitoring dashboard for OpenWrt/GL.iNet)
  48. Usage: sh install.sh [options]
  49. --version=X.Y.Z version to install (default: latest stable release)
  50. --demo install in demo mode with sample data (DEMO_MODE=1)
  51. --unattended no questions (automatic when there's no TTY)
  52. --dry-run describe each step without touching the system
  53. --uninstall remove service, binary and user (keeps $STATE_DIR)
  54. --purge with --uninstall: also remove data and configuration
  55. -h, --help this help
  56. Update = re-run this script (your data and .env are preserved).
  57. Repo: https://github.com/$GH_REPO
  58. EOF
  59. exit 0
  60. }
  61. for arg in "$@"; do
  62. case "$arg" in
  63. --version=*) NETPULSE_VERSION="${arg#*=}" ;;
  64. --demo) DEMO=1 ;;
  65. --unattended) UNATTENDED=1 ;;
  66. --dry-run) DRY_RUN=1 ;;
  67. --uninstall) UNINSTALL=1 ;;
  68. --purge) PURGE=1 ;;
  69. -h|--help) usage ;;
  70. *) fatal 10 "unknown option: $arg (try --help)" ;;
  71. esac
  72. done
  73. [ -t 0 ] || UNATTENDED=1 # pipe-to-shell: never prompt
  74. # ------------------------------------------------------- interactive helpers -
  75. tty_ok() { (exec 3<>/dev/tty) 2>/dev/null; }
  76. # ask_yes_no "question" [default: 0=no, 1=yes] — prompts on /dev/tty; returns 0/1.
  77. # Non-interactive (--unattended or no TTY): returns the default silently.
  78. ask_yes_no() {
  79. _q=$1; _def=${2:-0}
  80. [ "$UNATTENDED" -eq 1 ] && return "$_def"
  81. tty_ok || return "$_def"
  82. if [ "$_def" -eq 1 ]; then _hint="Y/n"; else _hint="y/N"; fi
  83. while :; do
  84. printf '%s [%s] ' "$_q" "$_hint" > /dev/tty
  85. IFS= read -r _r < /dev/tty || _r=""
  86. case "$(printf '%s' "$_r" | tr '[:upper:]' '[:lower:]')" in
  87. "") return "$_def" ;;
  88. y|yes|s|si) return 0 ;;
  89. n|no) return 1 ;;
  90. *) printf 'Please answer y or n.\n' > /dev/tty ;;
  91. esac
  92. done
  93. }
  94. # -------------------------------------------------------------- elevation ---
  95. if [ "$(id -u)" -eq 0 ]; then SUDO=""
  96. elif command -v sudo >/dev/null 2>&1; then SUDO="sudo -E"
  97. elif command -v doas >/dev/null 2>&1; then SUDO="doas"
  98. else fatal 22 "I need root (or sudo/doas). Download the script and run it as root: su -c 'sh install.sh'"
  99. fi
  100. # --------------------------------------------------------------- uninstall --
  101. if [ "$UNINSTALL" -eq 1 ]; then
  102. info "uninstalling $APP_NAME"
  103. if [ -f "/etc/systemd/system/$SERVICE_NAME.service" ]; then
  104. run $SUDO systemctl stop "$SERVICE_NAME" 2>/dev/null || true
  105. run $SUDO systemctl disable "$SERVICE_NAME" 2>/dev/null || true
  106. run $SUDO rm -f "/etc/systemd/system/$SERVICE_NAME.service"
  107. # Units de reinicio bajo demanda (issue #4): si existen, quitarlas
  108. if [ -f "/etc/systemd/system/$SERVICE_NAME-restart.path" ]; then
  109. run $SUDO systemctl disable --now "$SERVICE_NAME-restart.path" 2>/dev/null
  110. run $SUDO rm -f "/etc/systemd/system/$SERVICE_NAME-restart.path" \
  111. "/etc/systemd/system/$SERVICE_NAME-restart.service"
  112. fi
  113. # Auto-update estable (#480): unidades + helper + marcadores residuales
  114. if [ -f "/etc/systemd/system/$SERVICE_NAME-stable-update.path" ]; then
  115. run $SUDO systemctl disable --now "$SERVICE_NAME-stable-update.path" 2>/dev/null
  116. run $SUDO rm -f "/etc/systemd/system/$SERVICE_NAME-stable-update.path" \
  117. "/etc/systemd/system/$SERVICE_NAME-stable-update.service" \
  118. "$INSTALL_DIR/$APP_NAME-stable-apply"
  119. run $SUDO rm -f "$STATE_DIR/data/.stable-update" \
  120. "$STATE_DIR/data/.update-applied" "$STATE_DIR/data/.stable-update.error"
  121. fi
  122. run $SUDO systemctl daemon-reload
  123. ok "systemd unit removed"
  124. fi
  125. run $SUDO rm -f "$INSTALL_DIR/$BIN_NAME" "$INSTALL_DIR/$BIN_NAME.bak"
  126. ok "binary removed from $INSTALL_DIR"
  127. if id "$APP_NAME" >/dev/null 2>&1; then
  128. run $SUDO userdel "$APP_NAME" 2>/dev/null || warn "could not delete user $APP_NAME"
  129. ok "system user removed"
  130. fi
  131. # userdel leaves the login group behind whenever it has other members
  132. # (the collector user joins it) or the distro keeps it; the leftover
  133. # group breaks the next install (#467).
  134. if getent group "$APP_NAME" >/dev/null 2>&1; then
  135. run $SUDO groupdel "$APP_NAME" 2>/dev/null || warn "could not delete group $APP_NAME (still in use?)"
  136. ok "system group removed"
  137. fi
  138. if [ "$PURGE" -eq 1 ]; then
  139. run $SUDO rm -rf "$STATE_DIR"
  140. ok "data and configuration removed (--purge)"
  141. else
  142. info "data kept in $STATE_DIR (remove with --purge)"
  143. fi
  144. ok "$APP_NAME uninstalled"
  145. exit 0
  146. fi
  147. # --------------------------------------------------------------- detection --
  148. . /etc/os-release 2>/dev/null || true
  149. OS_PRETTY="${PRETTY_NAME:-$(uname -s)}"
  150. ARCH=$(uname -m)
  151. case "$ARCH" in
  152. x86_64|amd64) GOARCH=amd64 ;;
  153. aarch64|arm64) GOARCH=arm64 ;;
  154. armv7l|armv7) GOARCH=armv7 ;;
  155. *) fatal 20 "unsupported architecture: $ARCH (released: amd64, arm64, armv7)"
  156. esac
  157. if [ ! -d /run/systemd/system ] || ! command -v systemctl >/dev/null 2>&1; then
  158. fatal 23 "NetPulse needs systemd (this machine doesn't run it). See https://github.com/$GH_REPO for manual setup"
  159. fi
  160. info "detected: $OS_PRETTY · linux/$GOARCH · systemd"
  161. info "install.sh version: $INSTALLER_VERSION"
  162. if command -v curl >/dev/null 2>&1; then FETCH="curl -fsSL --retry 3 --connect-timeout 10"
  163. elif command -v wget >/dev/null 2>&1; then FETCH="wget -q -O-"
  164. else fatal 21 "I need curl or wget (install it with your package manager)"
  165. fi
  166. fetch_to() { $FETCH "$1" > "$2"; }
  167. command -v sha256sum >/dev/null 2>&1 || fatal 21 "missing sha256sum (coreutils package)"
  168. # ------------------------------------------------- disk / memory pre-flight --
  169. AVAIL_MB=$(df -Pm / 2>/dev/null | awk 'NR==2 {print $4}' || true)
  170. if [ -n "${AVAIL_MB:-}" ]; then
  171. [ "$AVAIL_MB" -lt 150 ] && fatal 24 "not enough disk space: ${AVAIL_MB} MB free (minimum 150 MB)"
  172. [ "$AVAIL_MB" -lt 300 ] && warn "low disk space: ${AVAIL_MB} MB free (recommended: 300+ MB)"
  173. ok "disk space: ${AVAIL_MB} MB free"
  174. fi
  175. MEM_MB=$(awk '/^MemAvailable:/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || true)
  176. if [ -n "${MEM_MB:-}" ] && [ "$MEM_MB" -lt 128 ]; then
  177. warn "low memory: ${MEM_MB} MB available — NetPulse needs very little, but 128+ MB is recommended"
  178. fi
  179. # ------------------------------------------------------ port pre-flight -----
  180. port_in_use() {
  181. if command -v ss >/dev/null 2>&1; then
  182. ss -tln 2>/dev/null | awk '{print $4}' | grep -qE "[:.]${1}\$"
  183. elif command -v netstat >/dev/null 2>&1; then
  184. netstat -tln 2>/dev/null | awk '{print $4}' | grep -qE "[:.]${1}\$"
  185. else
  186. return 1 # can't check: assume free
  187. fi
  188. }
  189. pick_port() {
  190. _p=$1; _end=$((_p + 20))
  191. while [ "$_p" -le "$_end" ]; do
  192. if ! port_in_use "$_p"; then printf '%s' "$_p"; return 0; fi
  193. _p=$((_p + 1))
  194. done
  195. return 1
  196. }
  197. # choose_port WANT — interactive (TTY): asks which port to use, suggesting the
  198. # next free one and rejecting busy/invalid answers. Non-interactive: prints the
  199. # next free port. Prints the chosen port on stdout; fails if none is free.
  200. choose_port() {
  201. _want=$1
  202. _next=$(pick_port "$((_want + 1))") || _next=""
  203. if [ "$UNATTENDED" -eq 0 ] && tty_ok; then
  204. while :; do
  205. printf 'Port %s is already in use.\nWhich port should %s listen on? [%s] ' \
  206. "$_want" "$APP_NAME" "${_next:-none free}" > /dev/tty
  207. IFS= read -r _r < /dev/tty || _r=""
  208. _r="${_r:-$_next}"
  209. case "$_r" in
  210. ''|*[!0-9]*) printf 'Please enter a port number.\n' > /dev/tty; continue ;;
  211. esac
  212. if [ "$_r" -lt 1 ] || [ "$_r" -gt 65535 ]; then
  213. printf 'Out of range (1-65535).\n' > /dev/tty; continue
  214. fi
  215. if port_in_use "$_r"; then
  216. printf 'Port %s is also in use.\n' "$_r" > /dev/tty; continue
  217. fi
  218. printf '%s' "$_r"; return 0
  219. done
  220. fi
  221. [ -n "$_next" ] || return 1
  222. printf '%s' "$_next"
  223. }
  224. # Fresh install only: an upgrade keeps the port from the existing .env file.
  225. PORT="$DEFAULT_PORT"
  226. if [ ! -f "$STATE_DIR/.env" ]; then
  227. if port_in_use "$DEFAULT_PORT"; then
  228. PORT=$(choose_port "$DEFAULT_PORT") \
  229. || fatal 25 "port $DEFAULT_PORT is busy and no free port found in $((DEFAULT_PORT + 1))-$((DEFAULT_PORT + 21)) — set one manually in $STATE_DIR/.env after install"
  230. warn "port $DEFAULT_PORT is already in use — NetPulse will listen on $PORT instead"
  231. else
  232. ok "port $DEFAULT_PORT is free"
  233. fi
  234. fi
  235. # Demo mode (issue #4): solo con --demo explícito. El default es BD limpia;
  236. # la demo se activa después desde Ajustes (el botón llama a
  237. # POST /api/demo/enable y reinicia el servicio vía .restart-me).
  238. # --------------------------------------------------------- resolve version --
  239. if [ -z "$NETPULSE_VERSION" ]; then
  240. info "resolving latest stable version"
  241. NETPULSE_VERSION=$($FETCH "https://api.github.com/repos/$GH_REPO/releases/latest" \
  242. | grep -oE '"tag_name"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | cut -d'"' -f4) \
  243. || fatal 31 "could not resolve the latest version (GitHub rate-limit?). Use --version=X.Y.Z"
  244. [ -n "$NETPULSE_VERSION" ] || fatal 31 "no stable release found yet. Use --version=X.Y.Z"
  245. fi
  246. VERSION_NORM=$(echo "$NETPULSE_VERSION" | sed 's/^v//')
  247. case "$NETPULSE_VERSION" in
  248. v*) NETPULSE_TAG="$NETPULSE_VERSION" ;;
  249. *) NETPULSE_TAG="v$NETPULSE_VERSION" ;;
  250. esac
  251. ASSET="${BIN_NAME}_${VERSION_NORM}_linux_${GOARCH}.tar.gz"
  252. BASE_URL="https://github.com/$GH_REPO/releases/download/$NETPULSE_TAG"
  253. info "version: $NETPULSE_VERSION"
  254. # connectivity pre-flight BEFORE touching the system
  255. $FETCH "https://github.com/$GH_REPO" >/dev/null \
  256. || fatal 30 "no access to github.com (proxy? DNS? firewall?)"
  257. UPGRADING=0
  258. if [ -x "$INSTALL_DIR/$BIN_NAME" ]; then
  259. UPGRADING=1
  260. info "previous install detected: upgrade mode (data and .env are preserved)"
  261. fi
  262. # ---------------------------------------------------------- download+verify --
  263. TMP=$(mktemp -d) || fatal 34 "mktemp failed"
  264. cleanup() { rm -rf "$TMP"; return 0; }
  265. trap cleanup EXIT INT TERM
  266. info "downloading $ASSET"
  267. fetch_to "$BASE_URL/$ASSET" "$TMP/$ASSET" || fatal 32 "download failed: $BASE_URL/$ASSET"
  268. fetch_to "$BASE_URL/checksums.txt" "$TMP/checksums.txt" || fatal 32 "checksums.txt not found in release $NETPULSE_VERSION"
  269. [ -s "$TMP/$ASSET" ] || fatal 32 "downloaded asset is empty"
  270. SUM_FILE=$(sha256sum "$TMP/$ASSET" | awk '{print $1}')
  271. SUM_REF=$(grep " $ASSET\$" "$TMP/checksums.txt" | awk '{print $1}')
  272. [ -n "$SUM_REF" ] || fatal 33 "$ASSET not listed in checksums.txt"
  273. [ "$SUM_FILE" = "$SUM_REF" ] || fatal 33 "sha256 MISMATCH for $ASSET — corrupt or tampered download"
  274. ok "sha256 verified"
  275. tar -tzf "$TMP/$ASSET" >/dev/null 2>&1 || fatal 34 "tarball is corrupt"
  276. tar -xzf "$TMP/$ASSET" -C "$TMP"
  277. [ -s "$TMP/$BIN_NAME" ] || fatal 34 "tarball does not contain $BIN_NAME"
  278. # ------------------------------------------------------------------ install --
  279. run $SUDO install -d -m 0755 "$INSTALL_DIR"
  280. if [ "$UPGRADING" -eq 1 ]; then
  281. run $SUDO cp -a "$INSTALL_DIR/$BIN_NAME" "$INSTALL_DIR/$BIN_NAME.bak"
  282. info "previous binary backed up: $INSTALL_DIR/$BIN_NAME.bak"
  283. fi
  284. run $SUDO install -T -m 0755 "$TMP/$BIN_NAME" "$INSTALL_DIR/$BIN_NAME"
  285. ok "binary installed at $INSTALL_DIR/$BIN_NAME"
  286. if ! id "$APP_NAME" >/dev/null 2>&1; then
  287. # Reinstall on a box where the group survived a previous uninstall
  288. # (#467): reuse the existing group instead of dying with
  289. # "useradd: group netpulse exists".
  290. if getent group "$APP_NAME" >/dev/null 2>&1; then
  291. run $SUDO useradd --system -g "$APP_NAME" --home-dir "$STATE_DIR" --shell /usr/sbin/nologin "$APP_NAME"
  292. else
  293. run $SUDO useradd --system --home-dir "$STATE_DIR" --shell /usr/sbin/nologin "$APP_NAME"
  294. fi
  295. ok "system user $APP_NAME created"
  296. fi
  297. run $SUDO install -d -m 0750 -o "$APP_NAME" -g "$APP_NAME" "$STATE_DIR"
  298. # SELinux: context fix, degrade to warning
  299. if command -v getenforce >/dev/null 2>&1 && [ "$(getenforce)" = "Enforcing" ]; then
  300. run $SUDO chcon -t bin_t "$INSTALL_DIR/$BIN_NAME" 2>/dev/null \
  301. || warn "SELinux Enforcing: if the service fails, check 'ausearch -m avc -ts recent'"
  302. fi
  303. # Initial config ONLY on fresh install (upgrades never touch .env or data)
  304. if [ ! -f "$STATE_DIR/.env" ]; then
  305. # #895: alfabeto sin caracteres ambiguos (sin 0/O ni 1/l/I) para que la
  306. # password inicial no se confunda en fuentes de terminal. 57 símbolos ×
  307. # 16 caracteres ≈ 94 bits de entropía.
  308. ADMIN_PASS=$(LC_ALL=C tr -dc 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' < /dev/urandom | head -c 16)
  309. if [ "$DRY_RUN" -eq 1 ]; then info "[dry-run] would generate $STATE_DIR/.env (0600, random admin password, PORT=$PORT, DEMO_MODE=$DEMO)"; else
  310. $SUDO tee "$STATE_DIR/.env" >/dev/null <<EOF
  311. PORT=$PORT
  312. DATA_DIR=./data
  313. NETPULSE_BIND=127.0.0.1
  314. AUTH_USER=admin
  315. AUTH_PASS=$ADMIN_PASS
  316. DEMO_MODE=$DEMO
  317. SSH_KEY_PATH=$STATE_DIR/.ssh/id_ed25519
  318. EOF
  319. $SUDO chmod 0600 "$STATE_DIR/.env"
  320. $SUDO chown "$APP_NAME:$APP_NAME" "$STATE_DIR/.env"
  321. fi
  322. FRESH_CREDENTIALS=1
  323. else
  324. FRESH_CREDENTIALS=0
  325. PORT=$(sed -n 's/^PORT=//p' "$STATE_DIR/.env" | head -1)
  326. PORT="${PORT:-$DEFAULT_PORT}"
  327. DEMO=$(sed -n 's/^DEMO_MODE=//p' "$STATE_DIR/.env" | head -1)
  328. DEMO="${DEMO:-0}"
  329. info "existing config kept ($STATE_DIR/.env)"
  330. fi
  331. # ----------------------------------------------------------------- service --
  332. if [ "$DRY_RUN" -eq 1 ]; then info "[dry-run] would write systemd unit + enable --now"; else
  333. $SUDO tee "/etc/systemd/system/$SERVICE_NAME.service" >/dev/null <<EOF
  334. [Unit]
  335. Description=NetPulse — network monitoring dashboard (OpenWrt/GL.iNet)
  336. After=network-online.target
  337. Wants=network-online.target
  338. [Service]
  339. Type=simple
  340. User=$APP_NAME
  341. Group=$APP_NAME
  342. WorkingDirectory=$STATE_DIR
  343. ExecStart=$INSTALL_DIR/$BIN_NAME
  344. Restart=on-failure
  345. RestartSec=5
  346. NoNewPrivileges=true
  347. ProtectSystem=strict
  348. ProtectHome=read-only
  349. PrivateTmp=true
  350. LockPersonality=true
  351. RemoveIPC=true
  352. StateDirectory=$APP_NAME
  353. UMask=007
  354. [Install]
  355. WantedBy=multi-user.target
  356. EOF
  357. # Unidad de reinicio bajo demanda (issue #4 + updater): una unit .path
  358. # vigila $STATE_DIR/data/.restart-me; cuando el servidor lo toca (p.ej.
  359. # POST /api/demo/enable) este oneshot lo borra y reinicia el servicio.
  360. $SUDO tee "/etc/systemd/system/$SERVICE_NAME-restart.path" >/dev/null <<EOF
  361. [Unit]
  362. Description=Reinicia $SERVICE_NAME cuando el servidor toca .restart-me
  363. [Path]
  364. PathChanged=$STATE_DIR/data/.restart-me
  365. [Install]
  366. WantedBy=multi-user.target
  367. EOF
  368. $SUDO tee "/etc/systemd/system/$SERVICE_NAME-restart.service" >/dev/null <<EOF
  369. [Unit]
  370. Description=Reinicio de $SERVICE_NAME solicitado por el servidor
  371. [Service]
  372. Type=oneshot
  373. ExecStart=/bin/sh -c "rm -f $STATE_DIR/data/.restart-me; /bin/systemctl restart $SERVICE_NAME.service"
  374. EOF
  375. # Auto-update estable (#480): el servidor deja el binario nuevo en
  376. # escena + marcador .stable-update; esta unit .path dispara el helper
  377. # root que verifica, hace swap y reinicia con rollback.
  378. $SUDO tee "/etc/systemd/system/$SERVICE_NAME-stable-update.path" >/dev/null <<EOF
  379. [Unit]
  380. Description=Vigila el marcador de auto-update estable de $SERVICE_NAME
  381. [Path]
  382. PathChanged=$STATE_DIR/data/.stable-update
  383. [Install]
  384. WantedBy=multi-user.target
  385. EOF
  386. $SUDO tee "/etc/systemd/system/$SERVICE_NAME-stable-update.service" >/dev/null <<EOF
  387. [Unit]
  388. Description=Aplica el update estable de $SERVICE_NAME (swap+restart)
  389. [Service]
  390. Type=oneshot
  391. Environment=STATE_DIR=$STATE_DIR
  392. Environment=SERVER_BIN=$INSTALL_DIR/$BIN_NAME
  393. Environment=SERVICE=$SERVICE_NAME
  394. ExecStart=$INSTALL_DIR/$APP_NAME-stable-apply
  395. EOF
  396. $SUDO tee "$INSTALL_DIR/$APP_NAME-stable-apply" >/dev/null <<'EOF_HELPER'
  397. #!/bin/sh
  398. # netpulse-stable-apply — helper root del auto-update estable (#480).
  399. # Lo dispara netpulse-stable-update.path cuando el servidor deja el binario
  400. # nuevo en escena con el marcador .stable-update (target/sha256/staged).
  401. # Reverifica el sha256, swap atómico, reinicio y healthcheck; rollback si
  402. # el servicio no vuelve a levantar. Sin curl, acepta sin verificar salud.
  403. set -u
  404. STATE_DIR="${STATE_DIR:-/var/lib/netpulse}"
  405. SERVER_BIN="${SERVER_BIN:-/usr/local/bin/netpulse}"
  406. SERVICE="${SERVICE:-netpulse}"
  407. DATA_DIR="$STATE_DIR/data"
  408. MARKER="$DATA_DIR/.stable-update"
  409. APPLIED="$DATA_DIR/.update-applied"
  410. ERRFILE="$DATA_DIR/.stable-update.error"
  411. BACKUP="$SERVER_BIN.bak-selfupdate"
  412. LOG_TAG="netpulse-stable-apply"
  413. log() { logger -t "$LOG_TAG" "$*" 2>/dev/null || echo "$LOG_TAG: $*"; }
  414. fail() {
  415. log "ERROR: $*"
  416. rm -f "$MARKER"
  417. echo "$*" > "$ERRFILE" 2>/dev/null || true
  418. exit 1
  419. }
  420. [ -f "$MARKER" ] || exit 0
  421. target=""; sha=""; staged=""
  422. while IFS='=' read -r k v; do
  423. case "$k" in
  424. target) target="$v" ;;
  425. sha256) sha="$v" ;;
  426. staged) staged="$v" ;;
  427. esac
  428. done < "$MARKER"
  429. [ -n "$target" ] && [ -n "$sha" ] && [ -n "$staged" ] || fail "stable_marker_invalid"
  430. case "$target" in v[0-9]*) ;; *) fail "stable_marker_invalid" ;; esac
  431. [ -f "$staged" ] || fail "stable_marker_invalid"
  432. echo "$sha $staged" | sha256sum -c - >/dev/null 2>&1 || fail "stable_checksum_mismatch"
  433. cp -a "$SERVER_BIN" "$BACKUP" 2>/dev/null || true
  434. install -T -m 0755 "$staged" "$SERVER_BIN" || fail "stable_install_failed"
  435. # Marcador de éxito ANTES del reinicio (patrón #444): el arranque nuevo lo
  436. # usa para confirmar el apply en el historial.
  437. printf '%s\n' "$target" > "$APPLIED"
  438. rm -f "$MARKER" "$staged"
  439. log "swap a $target hecho; reiniciando $SERVICE"
  440. systemctl restart "$SERVICE.service" || fail "stable_install_failed"
  441. if ! command -v curl >/dev/null 2>&1; then
  442. log "curl no disponible; healthcheck omitido"
  443. rm -f "$ERRFILE"
  444. exit 0
  445. fi
  446. PORT=""
  447. [ -f "$STATE_DIR/.env" ] && PORT=$(sed -n 's/^PORT=//p' "$STATE_DIR/.env" | head -1)
  448. PORT="${PORT:-3000}"
  449. # Budget generoso: el stop del servicio puede tardar hasta TimeoutStopSec
  450. # (90 s) si un tick del poller queda atascado en SNMP lentos (#481), más el
  451. # arranque con primer poll en curso.
  452. i=0
  453. while [ "$i" -lt 70 ]; do
  454. if curl -fsS --max-time 3 "http://127.0.0.1:$PORT/api/health" >/dev/null 2>&1; then
  455. log "healthcheck OK tras actualizar a $target"
  456. rm -f "$ERRFILE"
  457. exit 0
  458. fi
  459. i=$((i + 1))
  460. sleep 3
  461. done
  462. log "healthcheck falló tras 210s; rollback a $BACKUP"
  463. cp -a "$BACKUP" "$SERVER_BIN" 2>/dev/null || true
  464. systemctl restart "$SERVICE.service" 2>/dev/null || true
  465. rm -f "$APPLIED"
  466. fail "stable_healthcheck_failed"
  467. EOF_HELPER
  468. $SUDO chmod 0755 "$INSTALL_DIR/$APP_NAME-stable-apply"
  469. fi
  470. run $SUDO systemctl daemon-reload
  471. if [ "$UPGRADING" -eq 1 ]; then run $SUDO systemctl restart "$SERVICE_NAME"
  472. else run $SUDO systemctl enable --now "$SERVICE_NAME"; fi
  473. run $SUDO systemctl enable --now "$SERVICE_NAME-restart.path" 2>/dev/null \
  474. || warn "could not enable $SERVICE_NAME-restart.path (demo/update auto-restart)"
  475. run $SUDO systemctl enable --now "$SERVICE_NAME-stable-update.path" 2>/dev/null \
  476. || warn "could not enable $SERVICE_NAME-stable-update.path (stable self-update)"
  477. if [ "$DRY_RUN" -eq 0 ]; then
  478. sleep 3
  479. if ! $SUDO systemctl is-active --quiet "$SERVICE_NAME"; then
  480. err "service failed to start; diagnostics:"
  481. $SUDO systemctl status "$SERVICE_NAME" --no-pager || true
  482. $SUDO journalctl -u "$SERVICE_NAME" -n 50 --no-pager || true
  483. exit 40
  484. fi
  485. ok "service $SERVICE_NAME active"
  486. if command -v curl >/dev/null 2>&1; then
  487. curl -fsS --max-time 5 "http://127.0.0.1:$PORT/api/health" >/dev/null 2>&1 \
  488. && ok "HTTP health check OK on :$PORT" \
  489. || warn "service is up but http://127.0.0.1:$PORT didn't answer yet (give it a few seconds)"
  490. fi
  491. fi
  492. # ------------------------------------------------------------------ summary --
  493. printf '\n%s================ %s installed ================%s\n' "$C_G" "$APP_NAME" "$C_0"
  494. printf 'Version: %s%s\n' "$NETPULSE_VERSION" "$( [ "$UPGRADING" -eq 1 ] && echo " (upgrade — previous binary at $INSTALL_DIR/$BIN_NAME.bak)" || true)"
  495. printf 'Binary: %s\n' "$INSTALL_DIR/$BIN_NAME"
  496. printf 'Data: %s (SQLite, .env, SSH keypair)\n' "$STATE_DIR"
  497. # Access line (#1647): a fresh install without TLS binds the listener to
  498. # loopback, so the LAN URL was wrong. Honour NETPULSE_BIND when it is set.
  499. BIND_ADDR=$(sed -n 's/^NETPULSE_BIND=//p' "$STATE_DIR/.env" 2>/dev/null | head -1 || true)
  500. if [ -z "$BIND_ADDR" ]; then
  501. if [ -f "$STATE_DIR/data/netpulse.db" ]; then
  502. BIND_ADDR=0.0.0.0
  503. else
  504. BIND_ADDR=127.0.0.1
  505. fi
  506. fi
  507. if [ -n "$BIND_ADDR" ] && [ "$BIND_ADDR" != "0.0.0.0" ]; then
  508. printf 'Access: http://%s:%s (local only)\n' "$BIND_ADDR" "$PORT"
  509. printf ' LAN clients: add NETPULSE_BIND=0.0.0.0 to %s and restart\n' "$STATE_DIR/.env"
  510. else
  511. printf 'Access: http://<this-machine-ip>:%s\n' "$PORT"
  512. fi
  513. if [ "${FRESH_CREDENTIALS:-0}" -eq 1 ] && [ "$DRY_RUN" -eq 0 ]; then
  514. printf '\nInitial credentials (shown ONCE — change them after logging in):\n'
  515. printf ' user: admin\n password: %s\n' "$ADMIN_PASS"
  516. fi
  517. printf '\nUseful commands:\n'
  518. printf ' systemctl status %s\n journalctl -u %s -f\n' "$SERVICE_NAME" "$SERVICE_NAME"
  519. printf ' sh install.sh # update to the latest stable version\n'
  520. printf ' sh install.sh --uninstall\n'
  521. printf '\nNotes:\n'
  522. if [ "${DEMO:-0}" = "1" ]; then
  523. printf ' - DEMO MODE: sample network with 60+ devices; your routers are untouched.\n'
  524. printf ' To go live: set DEMO_MODE=0 in %s/.env and systemctl restart %s\n' "$STATE_DIR" "$SERVICE_NAME"
  525. else
  526. printf ' - To explore with sample data first: set DEMO_MODE=1 in %s/.env\n' "$STATE_DIR"
  527. printf ' and systemctl restart %s (demo mode never touches your routers).\n' "$SERVICE_NAME"
  528. fi
  529. printf ' - No firewall port was opened. If you need one:\n'
  530. printf ' firewall-cmd --permanent --add-port=%s/tcp && firewall-cmd --reload\n' "$PORT"
  531. printf ' ufw allow %s/tcp\n' "$PORT"
  532. printf ' - Live mode: authorize the server SSH public key on each router\n'
  533. printf ' (Settings shows it; append to /etc/dropbear/authorized_keys).\n'
  534. printf ' - Auto-update: the app downloads, verifies (sha256) and applies new\n'
  535. printf ' stable versions by itself (root helper %s-stable-apply; rollback\n' "$APP_NAME"
  536. printf ' if the health check fails). Re-run this script for manual updates.\n'
  537. printf '%s================================================%s\n\n' "$C_G" "$C_0"