This repository was archived by the owner on Sep 23, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·6482 lines (5807 loc) · 229 KB
/
Copy pathinstall.sh
File metadata and controls
executable file
·6482 lines (5807 loc) · 229 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# Hivekeep installer
# Usage: curl -fsSL https://raw.githubusercontent.com/MarlBurroW/hivekeep/main/install.sh | bash
# Or: HIVEKEEP_PORT=8080 bash install.sh
# Non-interactive: HIVEKEEP_NO_PROMPT=true bash install.sh
set -euo pipefail
# ─── Root detection ──────────────────────────────────────────────────────────
IS_ROOT=false
[ "$(id -u)" -eq 0 ] && IS_ROOT=true
# ─── Configurable via env vars ───────────────────────────────────────────────
if [ "$IS_ROOT" = true ]; then
HIVEKEEP_DIR="${HIVEKEEP_DIR:-/opt/hivekeep}"
HIVEKEEP_DATA_DIR="${HIVEKEEP_DATA_DIR:-/var/lib/hivekeep}"
HIVEKEEP_USER="${HIVEKEEP_USER:-hivekeep}"
else
HIVEKEEP_DIR="${HIVEKEEP_DIR:-$HOME/hivekeep}"
HIVEKEEP_DATA_DIR="${HIVEKEEP_DATA_DIR:-$HOME/.local/share/hivekeep}"
fi
HIVEKEEP_PORT="${HIVEKEEP_PORT:-3000}"
HIVEKEEP_PUBLIC_URL="${HIVEKEEP_PUBLIC_URL:-}"
HIVEKEEP_REPO="MarlBurroW/hivekeep"
# Explicitly requesting a branch implies the edge channel (tracking a branch
# head instead of release tags).
HIVEKEEP_BRANCH_EXPLICIT=false
[ -n "${HIVEKEEP_BRANCH:-}" ] && HIVEKEEP_BRANCH_EXPLICIT=true
HIVEKEEP_BRANCH="${HIVEKEEP_BRANCH:-main}"
# Update channel: stable (release tags, default) | edge (HEAD of main).
# Empty = auto-detect (existing checkout state, HIVEKEEP_BRANCH, else stable).
HIVEKEEP_CHANNEL="${HIVEKEEP_CHANNEL:-}"
HIVEKEEP_DRY_RUN=false
HIVEKEEP_QUIET="${HIVEKEEP_QUIET:-false}"
HIVEKEEP_START_TIME=""
HIVEKEEP_YES="${HIVEKEEP_YES:-false}"
# ─── Colors (auto-detect terminal support) ───────────────────────────────────
setup_colors() {
if [ "${NO_COLOR:-}" = "1" ] || [ "${HIVEKEEP_NO_COLOR:-}" = "true" ]; then
RED='' GREEN='' YELLOW='' CYAN='' DIM='' BOLD='' NC=''
elif [ -t 1 ] && [ -t 2 ]; then
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
DIM='\033[2m'
BOLD='\033[1m'
NC='\033[0m'
else
# Not a terminal (piped or redirected) — no colors
RED='' GREEN='' YELLOW='' CYAN='' DIM='' BOLD='' NC=''
fi
}
setup_colors
info() { [ "$HIVEKEEP_QUIET" = true ] && return; echo -e "${CYAN}▸${NC} $*"; }
success() { [ "$HIVEKEEP_QUIET" = true ] && return; echo -e "${GREEN}✓${NC} $*"; }
warn() { echo -e "${YELLOW}⚠${NC} $*" >&2; }
error() { echo -e "${RED}✗ ERROR:${NC} $*" >&2; exit 1; }
header() { [ "$HIVEKEEP_QUIET" = true ] && return; echo -e "\n${BOLD}$*${NC}"; }
# ─── Elapsed time tracking ──────────────────────────────────────────────────
start_timer() { HIVEKEEP_START_TIME="$(date +%s)"; }
# Returns human-readable elapsed time since start_timer() was called
format_elapsed() {
[ -z "$HIVEKEEP_START_TIME" ] && return
local now elapsed
now="$(date +%s)"
elapsed=$((now - HIVEKEEP_START_TIME))
if [ "$elapsed" -lt 5 ] 2>/dev/null; then
echo "< 5s"
elif [ "$elapsed" -lt 60 ] 2>/dev/null; then
echo "${elapsed}s"
elif [ "$elapsed" -lt 3600 ] 2>/dev/null; then
local m=$((elapsed / 60)) s=$((elapsed % 60))
if [ "$s" -gt 0 ]; then
echo "${m}m ${s}s"
else
echo "${m}m"
fi
else
local h=$((elapsed / 3600)) m=$(( (elapsed % 3600) / 60 ))
echo "${h}h ${m}m"
fi
}
# ─── Step progress (for main install flow) ───────────────────────────────────
STEP_CURRENT=0
STEP_TOTAL=0
step() {
STEP_CURRENT=$((STEP_CURRENT + 1))
[ "$HIVEKEEP_QUIET" = true ] && return
local progress=""
if [ "$STEP_TOTAL" -gt 0 ] 2>/dev/null; then
progress="${DIM}[${STEP_CURRENT}/${STEP_TOTAL}]${NC} "
fi
echo -e "\n${progress}${BOLD}$*${NC}"
}
# ─── Installer self-update check ─────────────────────────────────────────────
# When running from a local file (not piped via curl | bash), check if the
# installer itself is outdated compared to the remote version on GitHub.
# This prevents users from running stale install logic against a newer codebase.
check_installer_update() {
# Skip if piped (no local file to update), quiet mode, CI, or no-prompt
[ ! -t 0 ] && return 0
[ "$HIVEKEEP_QUIET" = true ] && return 0
[ "${HIVEKEEP_NO_PROMPT:-}" = "true" ] && return 0
[ "${CI:-}" = "true" ] && return 0
[ "${HIVEKEEP_SKIP_SELF_UPDATE:-}" = "true" ] && return 0
# Only check if we can identify the running script file
local self_path="${BASH_SOURCE[0]:-}"
[ -z "$self_path" ] && return 0
[ ! -f "$self_path" ] && return 0
# Compute local checksum
local local_hash=""
if command -v sha256sum &>/dev/null; then
local_hash="$(sha256sum "$self_path" 2>/dev/null | awk '{print $1}')"
elif command -v shasum &>/dev/null; then
local_hash="$(shasum -a 256 "$self_path" 2>/dev/null | awk '{print $1}')"
else
return 0 # can't compare without a hash tool
fi
[ -z "$local_hash" ] && return 0
# Fetch remote installer (lightweight: just the hash via a temp file)
local remote_url="https://raw.githubusercontent.com/$HIVEKEEP_REPO/$HIVEKEEP_BRANCH/install.sh"
local tmp_remote
tmp_remote="$(mktemp)"
if ! curl -fsSL --max-time 8 "$remote_url" -o "$tmp_remote" 2>/dev/null; then
rm -f "$tmp_remote"
return 0 # network issue, skip silently
fi
local remote_hash=""
if command -v sha256sum &>/dev/null; then
remote_hash="$(sha256sum "$tmp_remote" 2>/dev/null | awk '{print $1}')"
elif command -v shasum &>/dev/null; then
remote_hash="$(shasum -a 256 "$tmp_remote" 2>/dev/null | awk '{print $1}')"
fi
if [ -z "$remote_hash" ] || [ "$local_hash" = "$remote_hash" ]; then
rm -f "$tmp_remote"
return 0 # up to date or can't compare
fi
# Installer is outdated
echo -e "${YELLOW}⚠${NC} A newer version of the installer is available."
echo -en " ${CYAN}?${NC} ${BOLD}Update installer and restart?${NC} ${DIM}[Y/n]${NC}: " >/dev/tty
local answer
read -r answer </dev/tty || answer="y"
[ -z "$answer" ] && answer="y"
if [[ "$answer" =~ ^[Yy]$ ]]; then
cp "$tmp_remote" "$self_path"
chmod +x "$self_path"
rm -f "$tmp_remote"
success "Installer updated"
# Re-exec with same arguments, skip self-update to avoid loop
HIVEKEEP_SKIP_SELF_UPDATE=true exec bash "$self_path" "$@"
fi
rm -f "$tmp_remote"
}
# ─── Cleanup & signal handling ───────────────────────────────────────────────
SPINNER_PID=""
SPINNER_LOG=""
INTERRUPTED=false
cleanup_on_signal() {
INTERRUPTED=true
echo "" >&2
# Kill any running spinner background command
if [ -n "$SPINNER_PID" ] && kill -0 "$SPINNER_PID" 2>/dev/null; then
kill "$SPINNER_PID" 2>/dev/null
wait "$SPINNER_PID" 2>/dev/null || true
fi
SPINNER_PID=""
# Clean spinner line
printf "\r\033[K" >&2
# Remove temp log file
[ -n "$SPINNER_LOG" ] && rm -f "$SPINNER_LOG"
SPINNER_LOG=""
warn "Interrupted by user"
release_lock
# EXIT trap will fire next and handle rollback
exit 130
}
trap cleanup_on_signal INT TERM
# ─── Spinner for long-running commands ───────────────────────────────────────
# Usage: run_with_spinner "Installing dependencies..." command arg1 arg2
run_with_spinner() {
local label="$1"
shift
# If not a terminal or quiet mode, just run silently
if [ "$HIVEKEEP_QUIET" = true ]; then
"$@" >/dev/null 2>&1
return
fi
if [ ! -t 1 ] && [ ! -t 2 ]; then
info "$label"
"$@"
return
fi
local frames=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏")
local frame_count=${#frames[@]}
local i=0
local spin_start
spin_start="$(date +%s)"
SPINNER_LOG="$(mktemp)"
# Start the command in background, capturing output
"$@" > "$SPINNER_LOG" 2>&1 &
local cmd_pid=$!
SPINNER_PID=$cmd_pid
# Animate spinner while command runs (show elapsed time after 3s)
while kill -0 "$cmd_pid" 2>/dev/null; do
local elapsed_str=""
local now_s
now_s="$(date +%s)"
local elapsed_s=$((now_s - spin_start))
if [ "$elapsed_s" -ge 3 ]; then
if [ "$elapsed_s" -lt 60 ]; then
elapsed_str=" ${DIM}(${elapsed_s}s)${NC}"
else
local em=$((elapsed_s / 60)) es=$((elapsed_s % 60))
elapsed_str=" ${DIM}(${em}m ${es}s)${NC}"
fi
fi
printf "\r ${CYAN}%s${NC} %s%b" "${frames[$((i % frame_count))]}" "$label" "$elapsed_str" >&2
i=$((i + 1))
sleep 0.1
done
# Get exit code
wait "$cmd_pid"
local exit_code=$?
SPINNER_PID=""
# Compute final elapsed time
local final_elapsed=""
local end_s
end_s="$(date +%s)"
local total_s=$((end_s - spin_start))
if [ "$total_s" -ge 3 ]; then
if [ "$total_s" -lt 60 ]; then
final_elapsed=" ${DIM}(${total_s}s)${NC}"
else
local fm=$((total_s / 60)) fs=$((total_s % 60))
if [ "$fs" -gt 0 ]; then
final_elapsed=" ${DIM}(${fm}m ${fs}s)${NC}"
else
final_elapsed=" ${DIM}(${fm}m)${NC}"
fi
fi
fi
# Clear spinner line
printf "\r\033[K" >&2
if [ $exit_code -eq 0 ]; then
if [ -n "$final_elapsed" ]; then
[ "$HIVEKEEP_QUIET" = true ] && return
echo -e "${GREEN}✓${NC} ${label}${final_elapsed}" >&2
else
success "$label"
fi
else
echo -e "${RED}✗${NC} ${label}${final_elapsed}" >&2
echo "" >&2
echo -e "${DIM}Command output:${NC}" >&2
tail -20 "$SPINNER_LOG" >&2
rm -f "$SPINNER_LOG"
SPINNER_LOG=""
return $exit_code
fi
rm -f "$SPINNER_LOG"
SPINNER_LOG=""
return 0
}
# ─── Retry wrapper for flaky network operations ─────────────────────────────
# Usage: retry <max_attempts> <label> command arg1 arg2 ...
# Retries with exponential backoff (2s, 4s, 8s, ...) on failure.
retry() {
local max_attempts="$1"
local label="$2"
shift 2
local attempt=1
local delay=2
while true; do
if "$@" 2>&1; then
return 0
fi
if [ $attempt -ge "$max_attempts" ]; then
return 1
fi
warn "$label failed (attempt $attempt/$max_attempts) — retrying in ${delay}s..."
sleep $delay
delay=$((delay * 2))
attempt=$((attempt + 1))
done
}
# ─── Lockfile (prevent concurrent installer runs) ────────────────────────────
# Running two installers at the same time (e.g. two cron-triggered updates,
# or a user running install while an update is in progress) can corrupt the
# build, git state, or database. We use a lockfile to serialize access.
HIVEKEEP_LOCKFILE=""
acquire_lock() {
local lock_dir="${TMPDIR:-/tmp}"
HIVEKEEP_LOCKFILE="$lock_dir/hivekeep-installer.lock"
# Try to create the lockfile atomically
if ( set -o noclobber; echo "$$" > "$HIVEKEEP_LOCKFILE" ) 2>/dev/null; then
# We got the lock — register cleanup
return 0
fi
# Lockfile exists — check if the holder is still alive
local holder_pid
holder_pid="$(cat "$HIVEKEEP_LOCKFILE" 2>/dev/null || echo "")"
if [ -n "$holder_pid" ] && kill -0 "$holder_pid" 2>/dev/null; then
error "Another installer is already running (PID $holder_pid). Wait for it to finish or remove $HIVEKEEP_LOCKFILE"
fi
# Stale lockfile — previous run crashed without cleanup
warn "Removing stale lockfile (previous PID $holder_pid is gone)"
rm -f "$HIVEKEEP_LOCKFILE"
if ( set -o noclobber; echo "$$" > "$HIVEKEEP_LOCKFILE" ) 2>/dev/null; then
return 0
fi
# Race condition: another process grabbed it between our rm and write
error "Another installer is already running. Wait for it to finish or remove $HIVEKEEP_LOCKFILE"
}
release_lock() {
if [ -n "${HIVEKEEP_LOCKFILE:-}" ] && [ -f "${HIVEKEEP_LOCKFILE:-}" ]; then
# Only remove if we own it
local holder_pid
holder_pid="$(cat "$HIVEKEEP_LOCKFILE" 2>/dev/null || echo "")"
if [ "$holder_pid" = "$$" ]; then
rm -f "$HIVEKEEP_LOCKFILE"
fi
fi
HIVEKEEP_LOCKFILE=""
}
# ─── OS detection ────────────────────────────────────────────────────────────
detect_os() {
OS="$(uname -s)"
ARCH="$(uname -m)"
# Detect WSL
IS_WSL=false
if [ -f /proc/version ] && grep -qi 'microsoft\|wsl' /proc/version 2>/dev/null; then
IS_WSL=true
fi
case "$OS" in
Linux)
if [ -f /etc/os-release ]; then
# shellcheck disable=SC1091
. /etc/os-release
DISTRO="${ID:-unknown}"
DISTRO_LIKE="${ID_LIKE:-}" # exported for potential use by plugins
export DISTRO_LIKE
else
DISTRO="unknown"
DISTRO_LIKE=""
fi
# Check if systemd is actually available (WSL1 and some containers don't have it)
if command -v systemctl &>/dev/null && systemctl --version &>/dev/null 2>&1; then
INIT_SYSTEM="systemd"
else
INIT_SYSTEM="script"
fi
;;
Darwin)
DISTRO="macos"
DISTRO_LIKE=""
INIT_SYSTEM="launchd"
;;
*)
error "Unsupported OS: $OS. Hivekeep supports Linux and macOS."
;;
esac
local os_label="$OS ($DISTRO, $ARCH)"
if [ "$IS_WSL" = true ]; then
os_label="$OS ($DISTRO, $ARCH, WSL)"
fi
if [ "$IS_ROOT" = true ]; then
success "Detected OS: $os_label — running as root (system install)"
else
success "Detected OS: $os_label — running as $USER (user install)"
fi
if [ "$INIT_SYSTEM" = "script" ]; then
warn "systemd not available — will use a start/stop script instead"
if [ "$IS_WSL" = true ]; then
info "WSL detected. Service won't auto-start on boot; use the hivekeep script to start manually."
fi
fi
}
# ─── Install a system package (sudo only for this) ───────────────────────────
APT_UPDATED=false
install_pkg() {
local pkg="$1"
# Verify sudo is available when needed (not root, not brew)
if [ "$IS_ROOT" != true ] && ! command -v brew &>/dev/null; then
if ! command -v sudo &>/dev/null; then
echo "" >&2
error "$pkg is required but 'sudo' is not available to install it.\n\n ${BOLD}Fix:${NC} Install $pkg manually as root, then re-run the installer.\n ${DIM}Example: su -c 'apt-get update && apt-get install -y $pkg'${NC}"
fi
# Check that the user can actually sudo (cached credentials or NOPASSWD)
if ! sudo -n true 2>/dev/null; then
info "sudo password may be required to install $pkg"
fi
fi
info "Installing $pkg..."
if command -v apt-get &>/dev/null; then
# Refresh package cache once per installer run (stale caches cause failures on fresh systems)
if [ "$APT_UPDATED" != true ]; then
info "Refreshing package cache..."
if [ "$IS_ROOT" = true ]; then
apt-get update -qq 2>/dev/null || warn "apt-get update failed (continuing anyway)"
else
sudo apt-get update -qq 2>/dev/null || warn "apt-get update failed (continuing anyway)"
fi
APT_UPDATED=true
fi
if [ "$IS_ROOT" = true ]; then
apt-get install -y "$pkg" -q
else
sudo apt-get install -y "$pkg" -q
fi
elif command -v dnf &>/dev/null; then
sudo dnf install -y "$pkg" -q
elif command -v yum &>/dev/null; then
sudo yum install -y "$pkg" -q
elif command -v pacman &>/dev/null; then
sudo pacman -S --noconfirm "$pkg"
elif command -v apk &>/dev/null; then
sudo apk add --no-cache "$pkg"
elif command -v zypper &>/dev/null; then
sudo zypper install -y "$pkg"
elif command -v brew &>/dev/null; then
brew install "$pkg"
else
error "$pkg is required but could not be installed automatically. Please install it manually."
fi
success "$pkg installed"
}
# ─── Check prerequisites ─────────────────────────────────────────────────────
check_prerequisites() {
step "Checking prerequisites"
if ! command -v git &>/dev/null; then
install_pkg git
fi
success "git $(git --version | awk '{print $3}')"
if ! command -v curl &>/dev/null; then
install_pkg curl
fi
success "curl found"
# unzip is required by the Bun installer
if ! command -v unzip &>/dev/null; then
install_pkg unzip
fi
success "unzip found"
}
# ─── Pre-flight checks ───────────────────────────────────────────────────────
preflight_checks() {
step "Running pre-flight checks"
# Check available disk space (need ~500MB for clone + deps + build)
local install_parent
install_parent="$(dirname "$HIVEKEEP_DIR")"
mkdir -p "$install_parent" 2>/dev/null || true
local avail_kb
if avail_kb="$(df -k "$install_parent" 2>/dev/null | awk 'NR==2 {print $4}')"; then
if [ -n "$avail_kb" ] && [ "$avail_kb" -lt 512000 ] 2>/dev/null; then
local avail_mb=$((avail_kb / 1024))
error "Not enough disk space: ${avail_mb}MB available in $install_parent (need at least 500MB)"
elif [ -n "$avail_kb" ] && [ "$avail_kb" -lt 1024000 ] 2>/dev/null; then
local avail_mb=$((avail_kb / 1024))
warn "Low disk space: ${avail_mb}MB available in $install_parent (recommended: 1GB+)"
else
success "Disk space OK"
fi
fi
# Check if target port is already in use (skip on update — our own service may be running)
if [ -d "$HIVEKEEP_DIR/.git" ]; then
: # skip port check on update
elif [ -n "${HIVEKEEP_PORT:-}" ]; then
local port_in_use=false
if command -v ss &>/dev/null; then
ss -tlnp 2>/dev/null | grep -q ":${HIVEKEEP_PORT} " && port_in_use=true
elif command -v lsof &>/dev/null; then
lsof -i ":${HIVEKEEP_PORT}" -sTCP:LISTEN &>/dev/null && port_in_use=true
elif command -v netstat &>/dev/null; then
netstat -tlnp 2>/dev/null | grep -q ":${HIVEKEEP_PORT} " && port_in_use=true
fi
if [ "$port_in_use" = true ]; then
warn "Port $HIVEKEEP_PORT is already in use. You may need to choose a different port."
warn "Set HIVEKEEP_PORT=<number> or change it during the configuration step."
else
success "Port $HIVEKEEP_PORT is available"
fi
fi
# Proactively warn about privileged ports (<1024) for non-root installs.
# Binding these requires root; a normal user install will otherwise fail at
# startup with an opaque permission error. Hoisted out of the install-only
# branch above so it also fires on updates and under -y/CI (where the
# configure wizard is skipped). Runs exactly once per preflight.
if [ -n "${HIVEKEEP_PORT:-}" ] && [ "$IS_ROOT" != true ] && [ "$HIVEKEEP_PORT" -lt 1024 ] 2>/dev/null; then
warn "Port $HIVEKEEP_PORT is a privileged port (<1024) and you are not root."
warn "A non-root service cannot bind it and will fail to start."
info "Pick a port >= 1024 (e.g. 3000), or expose port 80/443 with a reverse proxy"
info "(Caddy, nginx, Traefik) in front of Hivekeep. To run on the privileged port"
info "directly, re-run the installer as root."
fi
# Check available memory (Bun builds can OOM on small machines)
if [ "$OS" = "Linux" ] && [ -f /proc/meminfo ]; then
local mem_total_kb mem_avail_kb swap_total_kb
mem_total_kb="$(awk '/^MemTotal:/ {print $2}' /proc/meminfo 2>/dev/null || echo "")"
mem_avail_kb="$(awk '/^MemAvailable:/ {print $2}' /proc/meminfo 2>/dev/null || echo "")"
swap_total_kb="$(awk '/^SwapTotal:/ {print $2}' /proc/meminfo 2>/dev/null || echo "")"
if [ -n "$mem_total_kb" ]; then
local mem_total_mb=$((mem_total_kb / 1024))
local mem_avail_mb=0
[ -n "$mem_avail_kb" ] && mem_avail_mb=$((mem_avail_kb / 1024))
local swap_total_mb=0
[ -n "$swap_total_kb" ] && swap_total_mb=$((swap_total_kb / 1024))
local effective_mb=$((mem_avail_mb + swap_total_mb))
if [ "$mem_total_mb" -lt 512 ] 2>/dev/null; then
warn "Low total RAM: ${mem_total_mb}MB (minimum 512MB recommended for builds)"
if [ "$swap_total_mb" -lt 256 ] 2>/dev/null; then
warn "No swap or very little swap (${swap_total_mb}MB). The build may fail with out-of-memory."
info "Consider adding swap: sudo fallocate -l 1G /swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfile"
else
info "Swap available (${swap_total_mb}MB) — should help during build"
fi
elif [ "$effective_mb" -lt 384 ] 2>/dev/null; then
warn "Low available memory: ${mem_avail_mb}MB RAM + ${swap_total_mb}MB swap"
info "Close other processes or add swap if the build fails"
else
success "Memory OK (${mem_avail_mb}MB available, ${mem_total_mb}MB total)"
fi
fi
elif [ "$OS" = "Darwin" ]; then
local mem_bytes
mem_bytes="$(sysctl -n hw.memsize 2>/dev/null || echo "")"
if [ -n "$mem_bytes" ]; then
local mem_total_mb=$((mem_bytes / 1024 / 1024))
success "Memory OK (${mem_total_mb}MB total)"
fi
fi
# Show proxy config if set (useful for debugging corporate/firewall setups)
if [ -n "${HTTP_PROXY:-}${HTTPS_PROXY:-}${http_proxy:-}${https_proxy:-}" ]; then
local proxy_url="${HTTPS_PROXY:-${https_proxy:-${HTTP_PROXY:-${http_proxy:-}}}}"
info "Using proxy: $proxy_url"
fi
# Check internet connectivity (needed for git clone and bun install)
if curl -fsSL --max-time 5 https://github.com >/dev/null 2>&1; then
success "Internet connectivity OK"
else
# Provide more helpful diagnostics
if ! host github.com &>/dev/null 2>&1 && ! nslookup github.com &>/dev/null 2>&1; then
error "DNS resolution failed for github.com. Check your network/DNS settings."
elif [ -n "${HTTP_PROXY:-}${HTTPS_PROXY:-}${http_proxy:-}${https_proxy:-}" ]; then
error "Cannot reach github.com through proxy. Verify your proxy settings."
else
error "Cannot reach github.com. Check your internet connection and firewall settings."
fi
fi
# Detect container environments (Docker, Podman, LXC, etc.)
local in_container=false
local container_type=""
if [ -f /.dockerenv ]; then
in_container=true
container_type="Docker"
elif [ -f /run/.containerenv ]; then
in_container=true
container_type="Podman"
elif grep -qa 'docker\|containerd' /proc/1/cgroup 2>/dev/null; then
in_container=true
container_type="Docker"
elif grep -qa 'lxc' /proc/1/cgroup 2>/dev/null; then
in_container=true
container_type="LXC"
elif [ -f /proc/1/sched ] 2>/dev/null; then
local pid1_name
pid1_name="$(head -1 /proc/1/sched 2>/dev/null | awk '{print $1}')"
if [ -n "$pid1_name" ] && [ "$pid1_name" != "systemd" ] && [ "$pid1_name" != "init" ]; then
# PID 1 is not init/systemd, likely a container
in_container=true
container_type="container"
fi
fi
if [ "$in_container" = true ]; then
warn "Running inside a $container_type environment"
# If this is a fresh install (not --docker mode), suggest Docker mode instead
if [ ! -d "$HIVEKEEP_DIR/.git" ]; then
info "Consider using ${BOLD}bash install.sh --docker${NC} instead, which generates"
info "a docker-compose.yml and avoids building inside the container."
fi
if [ "$INIT_SYSTEM" = "script" ]; then
info "systemd is not available; a start/stop script will be used."
info "The service won't auto-restart. Use a container restart policy or supervisor."
fi
fi
}
# ─── Interactive prompt (works with curl | bash via /dev/tty) ─────────────────
# Usage: prompt_value VAR_NAME "Question" "default value"
prompt_value() {
local var_name="$1"
local question="$2"
local default="$3"
local answer
# Auto-accept defaults in non-interactive / --yes mode
if [ "$HIVEKEEP_YES" = true ] || [ "${HIVEKEEP_NO_PROMPT:-}" = "true" ] || [ "${CI:-}" = "true" ]; then
printf -v "$var_name" '%s' "$default"
return
fi
echo -en " ${CYAN}?${NC} ${BOLD}${question}${NC} ${DIM}[${default}]${NC}: " >/dev/tty
read -r answer </dev/tty || answer=""
if [ -z "$answer" ]; then
answer="$default"
fi
printf -v "$var_name" '%s' "$answer"
}
# ─── Detect local IP ─────────────────────────────────────────────────────────
detect_local_ip() {
if [ "$OS" = "Linux" ]; then
hostname -I 2>/dev/null | awk '{print $1}' || echo "localhost"
else
ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null || echo "localhost"
fi
}
# ─── Configuration wizard ────────────────────────────────────────────────────
configure() {
local env_file="$HIVEKEEP_DATA_DIR/hivekeep.env"
# Skip on update if config already exists — don't overwrite user's settings
if [ "${IS_UPDATE:-false}" = true ] && [ -f "$env_file" ]; then
info "Existing config found at $env_file — keeping it"
# Still read the port from it for the summary
# shellcheck disable=SC1090
. "$env_file" 2>/dev/null || true
HIVEKEEP_PORT="${PORT:-$HIVEKEEP_PORT}"
HIVEKEEP_PUBLIC_URL="${PUBLIC_URL:-$HIVEKEEP_PUBLIC_URL}"
# Fallback: build URL from local IP if still empty
if [ -z "$HIVEKEEP_PUBLIC_URL" ]; then
local local_ip
local_ip="$(detect_local_ip)"
HIVEKEEP_PUBLIC_URL="http://${local_ip}:${HIVEKEEP_PORT}"
fi
return
fi
# Skip wizard if env vars already set or non-interactive
local skip_wizard=false
[ "${HIVEKEEP_NO_PROMPT:-}" = "true" ] && skip_wizard=true
[ "${CI:-}" = "true" ] && skip_wizard=true
# If all key vars were explicitly set via env, no need to ask
[ -n "${HIVEKEEP_PORT_EXPLICIT:-}" ] && [ -n "${HIVEKEEP_PUBLIC_URL}" ] && skip_wizard=true
if [ "$skip_wizard" = true ]; then
: # use defaults / env vars as-is
else
local local_ip
local_ip="$(detect_local_ip)"
echo ""
echo -e "${BOLD}Configuration${NC}"
echo -e "${DIM}Press Enter to accept the default value shown in brackets.${NC}"
echo ""
prompt_value HIVEKEEP_PORT "Port" "$HIVEKEEP_PORT"
# Warn if a non-root user picked a privileged port (<1024): it won't bind.
if [ "$IS_ROOT" != true ] && [ "$HIVEKEEP_PORT" -lt 1024 ] 2>/dev/null; then
warn "Port $HIVEKEEP_PORT is privileged (<1024) and you are not root, so the service won't be able to bind it."
warn "Choose a port >= 1024 (e.g. 3000), or put a reverse proxy in front of Hivekeep for ports 80/443."
fi
local default_url="http://${local_ip}:${HIVEKEEP_PORT}"
[ -n "$HIVEKEEP_PUBLIC_URL" ] && default_url="$HIVEKEEP_PUBLIC_URL"
prompt_value HIVEKEEP_PUBLIC_URL "Public URL (for webhooks & invite links)" "$default_url"
fi
# Fallback if public URL still empty
if [ -z "$HIVEKEEP_PUBLIC_URL" ]; then
local local_ip
local_ip="$(detect_local_ip)"
HIVEKEEP_PUBLIC_URL="http://${local_ip}:${HIVEKEEP_PORT}"
fi
# Write config file
mkdir -p "$HIVEKEEP_DATA_DIR"
cat > "$env_file" << ENV
# Hivekeep configuration — generated by installer
# Edit this file to change settings, then restart: systemctl --user restart hivekeep
NODE_ENV=production
PORT=${HIVEKEEP_PORT}
HOST=0.0.0.0
HIVEKEEP_DATA_DIR=${HIVEKEEP_DATA_DIR}
PUBLIC_URL=${HIVEKEEP_PUBLIC_URL}
ENV
chmod 600 "$env_file"
success "Config written to $env_file"
}
# ─── Install Bun ─────────────────────────────────────────────────────────────
# Minimum Bun version required (lockfileVersion 1 needs Bun 1.2+)
BUN_MIN_VERSION="1.2.0"
# Compare two semver strings: returns 0 if $1 >= $2, 1 otherwise
version_gte() {
local IFS='.'
local -a v1 v2
IFS='.' read -ra v1 <<< "$1"
IFS='.' read -ra v2 <<< "$2"
local i
for i in 0 1 2; do
local a="${v1[$i]:-0}" b="${v2[$i]:-0}"
if [ "$a" -gt "$b" ] 2>/dev/null; then return 0; fi
if [ "$a" -lt "$b" ] 2>/dev/null; then return 1; fi
done
return 0
}
ensure_bun() {
step "Checking Bun runtime"
# Validate architecture — Bun only supports x86_64 and aarch64 (ARM64)
case "$ARCH" in
x86_64|amd64)
: # supported
;;
aarch64|arm64)
: # supported
;;
armv7l|armv6l|armhf)
echo ""
error "Bun does not support 32-bit ARM ($ARCH).\n\n" \
" Hivekeep requires Bun, which only runs on x86_64 or ARM64 (aarch64).\n" \
" If you're on a Raspberry Pi, you need a 64-bit OS:\n" \
" ${DIM}• Raspberry Pi OS (64-bit): https://www.raspberrypi.com/software/${NC}\n" \
" ${DIM}• Ubuntu Server 64-bit for Pi: https://ubuntu.com/download/raspberry-pi${NC}\n\n" \
" Alternatively, use Docker (which handles architecture natively):\n" \
" ${DIM}bash install.sh --docker${NC}"
;;
i386|i686)
error "Bun does not support 32-bit x86 ($ARCH).\n\n" \
" Hivekeep requires a 64-bit system (x86_64 or ARM64).\n" \
" Alternatively, use Docker: ${DIM}bash install.sh --docker${NC}"
;;
*)
warn "Unknown architecture: $ARCH. Bun may not be available for this platform."
warn "If Bun installation fails, try Docker instead: bash install.sh --docker"
;;
esac
BUN_INSTALL="${BUN_INSTALL:-$HOME/.bun}"
export BUN_INSTALL
export PATH="$BUN_INSTALL/bin:$PATH"
if command -v bun &>/dev/null; then
local current_version
current_version="$(bun --version 2>/dev/null || echo "0.0.0")"
if version_gte "$current_version" "$BUN_MIN_VERSION"; then
success "Bun v${current_version}"
return 0
fi
warn "Bun v${current_version} is too old (need v${BUN_MIN_VERSION}+)"
info "Upgrading Bun..."
run_with_spinner "Upgrading Bun..." retry 3 "Bun upgrade" bash -c 'curl -fsSL https://bun.sh/install | bash'
export PATH="$BUN_INSTALL/bin:$PATH"
hash -r 2>/dev/null || true
local new_version
new_version="$(bun --version 2>/dev/null || echo "0.0.0")"
if version_gte "$new_version" "$BUN_MIN_VERSION"; then
success "Bun upgraded: v${current_version} → v${new_version}"
else
error "Bun upgrade failed (got v${new_version}, need v${BUN_MIN_VERSION}+). Upgrade manually: https://bun.sh"
fi
return 0
fi
info "Installing Bun..."
run_with_spinner "Downloading and installing Bun..." retry 3 "Bun install" bash -c 'curl -fsSL https://bun.sh/install | bash'
export PATH="$BUN_INSTALL/bin:$PATH"
command -v bun &>/dev/null || error "Bun installation failed. Install manually: https://bun.sh"
local installed_version
installed_version="$(bun --version 2>/dev/null || echo "0.0.0")"
if ! version_gte "$installed_version" "$BUN_MIN_VERSION"; then
error "Installed Bun v${installed_version} is below minimum v${BUN_MIN_VERSION}. Please update manually: https://bun.sh"
fi
success "Bun v${installed_version} installed"
}
# ─── Backup database before update ───────────────────────────────────────────
BACKUP_DB_PATH=""
backup_database() {
local db_file="$HIVEKEEP_DATA_DIR/hivekeep.db"
[ ! -f "$db_file" ] && return
local backup_dir="$HIVEKEEP_DATA_DIR/backups"
mkdir -p "$backup_dir"
local timestamp
timestamp="$(date +%Y%m%d-%H%M%S)"
local version_tag
version_tag="$(git -C "$HIVEKEEP_DIR" describe --tags 2>/dev/null || git -C "$HIVEKEEP_DIR" rev-parse --short HEAD 2>/dev/null || echo "unknown")"
# Sanitize version for filename
version_tag="$(echo "$version_tag" | tr '/' '-')"
BACKUP_DB_PATH="$backup_dir/hivekeep-${version_tag}-${timestamp}.db"
# Use sqlite3 .backup if available (safe even if DB is in use), else cp
if command -v sqlite3 &>/dev/null; then
if sqlite3 "$db_file" ".backup '$BACKUP_DB_PATH'" 2>/dev/null; then
success "Database backed up (sqlite3): $(basename "$BACKUP_DB_PATH")"
else
cp "$db_file" "$BACKUP_DB_PATH"
success "Database backed up (copy): $(basename "$BACKUP_DB_PATH")"
fi
else
cp "$db_file" "$BACKUP_DB_PATH"
success "Database backed up (copy): $(basename "$BACKUP_DB_PATH")"
fi
# Also backup WAL/SHM if they exist (for cp-based backups)
if [ -f "${db_file}-wal" ]; then cp "${db_file}-wal" "${BACKUP_DB_PATH}-wal" 2>/dev/null || true; fi
if [ -f "${db_file}-shm" ]; then cp "${db_file}-shm" "${BACKUP_DB_PATH}-shm" 2>/dev/null || true; fi
# Prune old backups: keep last 5
local count
count="$(find "$backup_dir" -maxdepth 1 -name 'hivekeep-*.db' -type f 2>/dev/null | wc -l)"
if [ "$count" -gt 5 ] 2>/dev/null; then
find "$backup_dir" -maxdepth 1 -name 'hivekeep-*.db' -type f -printf '%T@ %p\n' 2>/dev/null \
| sort -n \
| head -n "$((count - 5))" \
| awk '{print $2}' \
| while IFS= read -r old; do
rm -f "$old" "${old}-wal" "${old}-shm"
done
info "Pruned old backups (keeping last 5)"
fi
}
# ─── Update channels ─────────────────────────────────────────────────────────
# stable: follows release tags (vX.Y.Z), uses prebuilt client assets from the
# GitHub release when available.
# edge: follows the HEAD of $HIVEKEEP_BRANCH (main), builds locally.
HIVEKEEP_TARGET_TAG=""
resolve_channel() {
# 1. Explicit --channel flag / HIVEKEEP_CHANNEL env wins
if [ -n "$HIVEKEEP_CHANNEL" ]; then
echo "$HIVEKEEP_CHANNEL"
return
fi
# 2. Explicitly requested branch = edge semantics
if [ "$HIVEKEEP_BRANCH_EXPLICIT" = true ]; then
echo "edge"
return
fi
# 3. Existing install: a branch checkout tracks that branch (edge), a
# detached HEAD (left by a tag checkout) tracks releases (stable).
if [ -d "$HIVEKEEP_DIR/.git" ]; then
local cur_branch
cur_branch="$(git -C "$HIVEKEEP_DIR" branch --show-current 2>/dev/null || echo "")"
if [ -n "$cur_branch" ]; then
echo "edge"
else
echo "stable"
fi
return
fi
# 4. Fresh install: stable
echo "stable"
}
# Newest non-prerelease vX.Y.Z tag. Prefers the local repo (after a fetch);
# falls back to the remote so it also works before cloning. Memoized: a single
# update flow resolves the tag several times (check, install, build) and each
# remote resolution is a network round-trip.
_LATEST_STABLE_TAG_CACHE=""
get_latest_stable_tag() {
if [ -n "$_LATEST_STABLE_TAG_CACHE" ]; then
echo "$_LATEST_STABLE_TAG_CACHE"
return
fi
local tags=""
if [ -d "${HIVEKEEP_DIR:-/nonexistent}/.git" ]; then
tags="$(git -C "$HIVEKEEP_DIR" tag -l 'v*' 2>/dev/null)"
fi
if [ -z "$tags" ]; then
tags="$(git ls-remote --tags --refs "https://github.com/$HIVEKEEP_REPO.git" 'v*' 2>/dev/null | awk -F/ '{print $NF}')"
fi
_LATEST_STABLE_TAG_CACHE="$(echo "$tags" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -1)"
echo "$_LATEST_STABLE_TAG_CACHE"
}
# Download the prebuilt client assets attached to a release by CI
# (hivekeep-client-vX.Y.Z.tar.gz + .sha256) and extract them into
# $HIVEKEEP_DIR/dist/client. Returns non-zero when unavailable or invalid so
# the caller can fall back to a local build.
download_prebuilt_client() {
local tag="$1"
[ -z "$tag" ] && return 1
local asset="hivekeep-client-${tag}.tar.gz"
local base="https://github.com/$HIVEKEEP_REPO/releases/download/${tag}"
local tmp
tmp="$(mktemp -d)" || return 1
if ! curl -fsSL --connect-timeout 10 --max-time 300 -o "$tmp/$asset" "$base/$asset" 2>/dev/null; then
rm -rf "$tmp"
return 1
fi
if ! curl -fsSL --connect-timeout 10 --max-time 60 -o "$tmp/$asset.sha256" "$base/$asset.sha256" 2>/dev/null; then
rm -rf "$tmp"
return 1
fi
# Verify the checksum (sha256sum on Linux, shasum on macOS)
local expected actual
expected="$(awk '{print $1}' "$tmp/$asset.sha256")"
if command -v sha256sum &>/dev/null; then
actual="$(sha256sum "$tmp/$asset" | awk '{print $1}')"
elif command -v shasum &>/dev/null; then
actual="$(shasum -a 256 "$tmp/$asset" | awk '{print $1}')"