-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathbootstrap.sh
More file actions
executable file
·4975 lines (4243 loc) · 166 KB
/
bootstrap.sh
File metadata and controls
executable file
·4975 lines (4243 loc) · 166 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
#!/bin/bash
#
#
# ▄▄▄▄▄▄
# ███▀▀▀██▄ nesaorg/bootstrap
# ███ ███ ███████ ███████ █████
# ███ ███ ██ ██ ██ ██
# ▄▄▄ ███ █████ ███████ ███████
# ███ ███ ██ ██ ██ ██
# ███ ███ ███████ ███████ ██ ██
#
#
# noteworthy conventions: variables that are exported to the config file or the container environment files are in all caps
#
# vars
#
trap 'trap " " SIGINT SIGTERM SIGHUP; kill 0; wait; sigterm_handler' SIGINT SIGTERM SIGHUP
# Store the real script path for restarts
# Handle running via process substitution (bash <(curl ...)) where BASH_SOURCE is /dev/fd/XX
_raw_script_path="${BASH_SOURCE[0]}"
if [[ "$_raw_script_path" == /dev/fd/* ]] || [[ "$_raw_script_path" == /proc/self/fd/* ]]; then
# Running from process substitution - save script to ~/.nesa for restarts
SCRIPT_PATH="${HOME}/.nesa/bootstrap.sh"
RUNNING_FROM_PIPE=true
# Save a copy of the script for restarts (download fresh copy)
mkdir -p "${HOME}/.nesa"
curl -sL "https://raw.githubusercontent.com/nesaorg/bootstrap/master/bootstrap.sh" -o "$SCRIPT_PATH" 2>/dev/null || true
chmod +x "$SCRIPT_PATH" 2>/dev/null || true
else
SCRIPT_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"
RUNNING_FROM_PIPE=false
fi
# Detect OS early for platform-specific code
OS_TYPE="$(uname -s)"
# ---- global bootstrap logging (captures ALL stdout/err while keeping the screen interactive) ----
DEFAULT_WORKDIR="${HOME}/.nesa"
LOG_DIR="${DEFAULT_WORKDIR}/logs"
ENV_DIR="${DEFAULT_WORKDIR}/env"
# Create directories with error handling
if ! mkdir -p "${DEFAULT_WORKDIR}" "${LOG_DIR}" "${ENV_DIR}" 2>/dev/null; then
echo "ERROR: Cannot create directory ${DEFAULT_WORKDIR}"
echo "Please check permissions on your home directory."
exit 1
fi
# Helper to restart the script - handles process substitution (bash <(curl...)) gracefully
restart_script() {
if [[ -f "$SCRIPT_PATH" ]]; then
exec bash "$SCRIPT_PATH"
else
# Fallback if script file doesn't exist
echo ""
echo "To return to the main menu, please re-run the bootstrap command:"
echo " bash <(curl -s https://raw.githubusercontent.com/nesaorg/bootstrap/master/bootstrap.sh)"
echo ""
exit 0
fi
}
# Mirror STDOUT and STDERR to file; only the copy to file is timestamped.
# This preserves gum's interactive UI on the terminal.
# exec > >(tee >(awk '{ printf "[%s] %s\n", strftime("%Y-%m-%dT%H:%M:%SZ"), $0; fflush() }' >> "${LOG_DIR}/bootstrap.log"))
# exec 2> >(tee >(awk '{ printf "[%s] %s\n", strftime("%Y-%m-%dT%H:%M:%SZ"), $0; fflush() }' >> "${LOG_DIR}/bootstrap.log") >&2)
# -----------------------------------------------------------------------------------------------
LOG_FILE="${LOG_DIR}/bootstrap.log"
# Truncate log file at session start - keeps only current session, prevents unbounded growth
# (silently skip if directory doesn't exist yet - will be created later or already exists)
: > "$LOG_FILE" 2>/dev/null || true
# Log ingestion settings - defined early so available for exit handler
INGEST_URL="${INGEST_URL:-https://ingester.nesa.ai/ingest}"
INGEST_API_KEY="${INGEST_API_KEY:-nesa-logs-v2-8bc28d5caeb84126f359d557c48ddb8c}"
export INGEST_URL INGEST_API_KEY
_ts() { date -u +"%Y-%m-%dT%H:%M:%SZ"; }
log_line() { { printf "[%s] %s\n" "$(_ts)" "$*" >>"$LOG_FILE"; } 2>/dev/null || true; }
log_stream() { while IFS= read -r line; do { printf "[%s] %s\n" "$(_ts)" "$line" >>"$LOG_FILE"; } 2>/dev/null; done; }
run_and_log() {
local title="$1"
shift
log_line "BEGIN: $title - $*"
if gum spin -s line --title "$title" -- "$@" 2> >(log_stream) | log_stream; then
log_line "END: $title (ok)"
return 0
else
log_line "END: $title (fail)"
return 1
fi
}
# Safe math helper - works on both GNU and BSD (Mac) awk
# Usage: safe_divide <numerator> <divisor> <decimals>
safe_divide() {
local num="${1:-0}"
local div="${2:-1}"
local dec="${3:-6}"
# Handle empty or non-numeric input
[ -z "$num" ] || [ "$num" = "" ] && num=0
[ -z "$div" ] || [ "$div" = "" ] || [ "$div" = "0" ] && div=1
awk -v n="$num" -v d="$div" -v p="$dec" 'BEGIN { printf "%.*f", p, n/d }'
}
# Safe multiply helper
# Usage: safe_multiply <num1> <num2> <decimals>
safe_multiply() {
local num1="${1:-0}"
local num2="${2:-1}"
local dec="${3:-0}"
[ -z "$num1" ] || [ "$num1" = "" ] && num1=0
[ -z "$num2" ] || [ "$num2" = "" ] && num2=1
awk -v a="$num1" -v b="$num2" -v p="$dec" 'BEGIN { printf "%.*f", p, a*b }'
}
# Safe JSON parsing helper
# Usage: safe_jq <json_string> <jq_filter> [default_value]
# Returns the jq result or default_value if parsing fails
safe_jq() {
local json="$1"
local filter="$2"
local default="${3:-}"
# Check if input looks like JSON (starts with { or [)
if [[ -z "$json" ]] || [[ ! "$json" =~ ^[[:space:]]*[\{\[] ]]; then
log_line "safe_jq: Invalid JSON input"
echo "$default"
return 1
fi
# Try to parse with jq
local result
result=$(echo "$json" | jq -r "$filter" 2>/dev/null)
local jq_exit=$?
# Check if jq failed or returned null/empty
if [[ $jq_exit -ne 0 ]] || [[ -z "$result" ]] || [[ "$result" == "null" ]]; then
log_line "safe_jq: jq filter '$filter' returned empty/null"
echo "$default"
return 1
fi
echo "$result"
return 0
}
# Fetch JSON from URL with error handling
# Usage: fetch_json <url> [timeout_seconds]
# Returns JSON string or empty on failure
fetch_json() {
local url="$1"
local timeout="${2:-10}"
local response
response=$(curl -sfS --connect-timeout "$timeout" --max-time "$((timeout * 3))" "$url" 2>/dev/null)
local curl_exit=$?
if [[ $curl_exit -ne 0 ]] || [[ -z "$response" ]]; then
log_line "fetch_json: Failed to fetch $url (curl exit: $curl_exit)"
echo ""
return 1
fi
# Validate it's JSON
if ! echo "$response" | jq empty 2>/dev/null; then
log_line "fetch_json: Response from $url is not valid JSON"
echo ""
return 1
fi
echo "$response"
return 0
}
# Append to log file (don't truncate on restart)
touch "${LOG_FILE}" 2>/dev/null || true
log_line "=== Bootstrap session started ==="
# Create env files if they don't exist
touch "${ENV_DIR}/base.env" "${ENV_DIR}/orchestrator.env" "${DEFAULT_WORKDIR}/.env" 2>/dev/null || {
echo "ERROR: Cannot create config files in ${ENV_DIR}"
echo "Please check permissions."
exit 1
}
sigterm_handler() {
printf "\n Aborting node setup. Cleaning up...\n"
# Add any additional cleanup tasks here
echo
exit 1
}
# Ship bootstrap logs to ingester on exit (if we have a private key)
# This ensures logs are captured even if containers never start
ship_bootstrap_logs() {
# Only ship if we have the essentials
local priv_key="${NODE_PRIV_KEY:-}"
local log_file="${LOG_FILE:-${HOME}/.nesa/logs/bootstrap.log}"
local ingest_url="$INGEST_URL"
local api_key="$INGEST_API_KEY"
# Try to load from orchestrator.env if not in memory
if [ -z "$priv_key" ] && [ -f "${ENV_DIR}/orchestrator.env" ]; then
priv_key=$(grep "^NODE_PRIV_KEY=" "${ENV_DIR}/orchestrator.env" 2>/dev/null | cut -d'=' -f2 | tr -d '"' | tr -d "'")
fi
# No key = can't sign = can't ship (silent to user, log to file only)
if [ -z "$priv_key" ]; then
log_line "[log-ship] no private key available, skipping"
return 0
fi
if [ ! -f "$log_file" ]; then
log_line "[log-ship] log file not found: $log_file"
return 0
fi
# Check if Python and ecdsa are available
if ! command -v python3 >/dev/null 2>&1; then
log_line "[log-ship] python3 not available, skipping"
return 0
fi
if ! python3 -c "import ecdsa, json, hashlib" 2>/dev/null; then
log_line "[log-ship] python ecdsa not available, skipping"
return 0
fi
log_line "[log-ship] shipping bootstrap logs..."
# Get node metadata
local node_id="${NODE_ID:-unknown}"
local moniker="${MONIKER:-unknown}"
local public_ip="${PUBLIC_IP:-0.0.0.0}"
# Try to load from orchestrator.env if not set
if [ "$node_id" = "unknown" ] && [ -f "${ENV_DIR}/orchestrator.env" ]; then
node_id=$(grep "^NODE_ID=" "${ENV_DIR}/orchestrator.env" 2>/dev/null | cut -d'=' -f2 | tr -d '"' | tr -d "'" || echo "unknown")
moniker=$(grep "^MONIKER=" "${ENV_DIR}/orchestrator.env" 2>/dev/null | cut -d'=' -f2 | tr -d '"' | tr -d "'" || echo "unknown")
fi
# Get public IP if not set
if [ "$public_ip" = "0.0.0.0" ]; then
public_ip=$(curl -s --max-time 5 https://api.ipify.org 2>/dev/null || echo "0.0.0.0")
fi
# Use Python to sign and format logs, generate auth headers, then POST with curl
local line_count=$(wc -l < "$log_file" 2>/dev/null || echo "0")
log_line "[log-ship] uploading $line_count log lines"
# Generate auth headers and log payload in one Python script, then curl
python3 << PYEOF > /tmp/nesa_log_payload.ndjson
import sys
import json
import hashlib
import time
import os
import ecdsa
priv_hex = "${priv_key}".strip()
if priv_hex.lower().startswith("0x"):
priv_hex = priv_hex[2:]
priv_bytes = bytes.fromhex(priv_hex)
sk = ecdsa.SigningKey.from_string(priv_bytes, curve=ecdsa.SECP256k1)
vk = sk.get_verifying_key()
pubkey = b'\x02' + vk.to_string()[:32] if vk.to_string()[-1] % 2 == 0 else b'\x03' + vk.to_string()[:32]
pubkey_hex = pubkey.hex()
# Generate auth headers for the HTTP request
auth_ts = int(time.time() * 1000)
auth_preimage = f"nesa-ingest-auth|{auth_ts}"
auth_digest = hashlib.sha256(auth_preimage.encode()).digest()
auth_sig = sk.sign_digest(auth_digest, sigencode=ecdsa.util.sigencode_der)
# Write auth headers to a file for curl to use
with open('/tmp/nesa_auth_headers.txt', 'w') as hf:
hf.write(f"X-Nesa-PubKey:{pubkey_hex}\n")
hf.write(f"X-Nesa-Timestamp:{auth_ts}\n")
hf.write(f"X-Nesa-Signature:{auth_sig.hex()}\n")
node_id = "${node_id}"
moniker = "${moniker}"
public_ip = "${public_ip}"
hostname = os.uname().nodename
log_file = "${log_file}"
seq = 1
with open(log_file, 'r', errors='replace') as f:
for line in f:
line = line.rstrip('\n')
if not line:
continue
ts_ms = int(time.time() * 1000)
payload = json.dumps({"line": line})
payload_hash = hashlib.sha256(payload.encode()).hexdigest()
signer_version = "2.0.0"
preimage = f"v=1\nsigner_version={signer_version}\npubkey={pubkey_hex}\nnode_id={node_id}\nmoniker={moniker}\npublic_ip={public_ip}\nstream_type=bootstrap\nstream_id=bootstrap-exit\nstream_name=bootstrap\nts={ts_ms}\nseq={seq}\nlevel=info\nhost={hostname}\npayload_hash={payload_hash}"
digest = hashlib.sha256(preimage.encode()).digest()
sig = sk.sign_digest(digest, sigencode=ecdsa.util.sigencode_der)
envelope = {
"v": 1,
"signer_version": signer_version,
"node": {"pubkey": pubkey_hex, "id": node_id, "moniker": moniker, "public_ip": public_ip},
"stream": {"type": "bootstrap", "id": "bootstrap-exit", "name": "bootstrap"},
"ts_unix_ms": ts_ms,
"seq": seq,
"level": "info",
"host": hostname,
"payload": json.loads(payload),
"payload_hash": payload_hash
}
record = {"envelope": envelope, "pubkey": pubkey_hex, "signature": sig.hex()}
print(json.dumps(record))
seq += 1
PYEOF
# Read auth headers and send with curl
if [ -f /tmp/nesa_auth_headers.txt ] && [ -f /tmp/nesa_log_payload.ndjson ]; then
local pubkey_header=$(grep "^X-Nesa-PubKey:" /tmp/nesa_auth_headers.txt)
local ts_header=$(grep "^X-Nesa-Timestamp:" /tmp/nesa_auth_headers.txt)
local sig_header=$(grep "^X-Nesa-Signature:" /tmp/nesa_auth_headers.txt)
# Send logs silently, capture response for logging only
local response
response=$(curl -s --max-time 30 -X POST \
-H "Content-Type: application/x-ndjson" \
-H "X-Nesa-API-Key:$api_key" \
-H "$pubkey_header" \
-H "$ts_header" \
-H "$sig_header" \
--data-binary @/tmp/nesa_log_payload.ndjson \
"$ingest_url" 2>/dev/null || echo "failed")
log_line "[log-ship] response: $response"
rm -f /tmp/nesa_auth_headers.txt /tmp/nesa_log_payload.ndjson
fi
log_line "[log-ship] done"
}
# Register exit handler to ship logs
trap 'ship_bootstrap_logs' EXIT
# Get terminal size with fallback for non-interactive terminals (SSH, tmux, etc.)
terminal_size=$(stty size 2>/dev/null || echo "24 80")
terminal_height="${terminal_size% *}"
terminal_width="${terminal_size#* }"
# Validate we got numbers, fallback if not
[[ "$terminal_height" =~ ^[0-9]+$ ]] || terminal_height=24
[[ "$terminal_width" =~ ^[0-9]+$ ]] || terminal_width=80
prompt_height=${PROMPT_HEIGHT:-1}
main_color=43
link_color=69
# Detect if running on a serial console or basic terminal with limited color support
# Can be forced with BASIC_TERMINAL=true or BASIC_TERMINAL=false environment variable
detect_basic_terminal() {
# Allow override via environment (both ways)
[[ "$BASIC_TERMINAL" == "true" ]] && return 0
[[ "$BASIC_TERMINAL" == "false" ]] && return 1
# WSL2 - use basic mode (numbered menus) for reliability until confirmed working
# Can override with BASIC_TERMINAL=false if gum works fine
if [[ -n "$WSL_DISTRO_NAME" ]] || [[ -n "$WSL_INTEROP" ]] || grep -qi microsoft /proc/version 2>/dev/null; then
return 0 # WSL = basic mode for safety
fi
# Check for serial console (ttyS*, ttyAMA*, ttyUSB*, etc.)
local tty_name
tty_name=$(tty 2>/dev/null || echo "")
case "$tty_name" in
/dev/ttyS*|/dev/ttyAMA*|/dev/ttyUSB*|/dev/hvc*|/dev/tty[0-9]*|/dev/console) return 0 ;;
esac
# If on pseudo-terminal (pts), generally fine
case "$tty_name" in
/dev/pts/*) return 1 ;; # pseudo-terminal, good
esac
# Check TERM variable for basic terminals
case "$TERM" in
dumb|vt100|vt102|vt220|vt320|linux|ansi|cons*|serial*) return 0 ;;
xterm*|screen*|tmux*|rxvt*|putty*) return 1 ;; # These support colors
esac
# No TERM set usually means basic terminal
[[ -z "$TERM" ]] && return 0
# Unknown tty but has TERM set - probably fine
return 1
}
# Detect light/dark terminal background
# COLORFGBG format: "fg;bg" - bg of 15, 7, or similar means light background
# Also check common light terminal indicators
detect_light_terminal() {
# Check COLORFGBG (set by some terminals like xterm, rxvt)
# Extract background value after the semicolon
if [[ -n "$COLORFGBG" ]]; then
local bg_color="${COLORFGBG##*;}"
case "$bg_color" in
15|7|6|9|10|11|12|14) return 0 ;; # light background colors
esac
fi
# Check for known light terminal profiles
case "$KONSOLE_PROFILE_NAME" in
*[Ll]ight*|*[Ww]hite*|*Solarized*[Ll]ight*) return 0 ;;
esac
case "$ITERM_PROFILE" in
*[Ll]ight*|*[Ww]hite*|*Solarized*[Ll]ight*) return 0 ;;
esac
# Check if terminal background color is set and appears light
case "$TERMINAL_BACKGROUND" in
[Ww]hite*|[Ll]ight*) return 0 ;;
esac
return 1 # assume dark
}
# Define theme-aware colors
if detect_basic_terminal; then
# Basic terminal - use simple ANSI colors (0-7) that work everywhere
dim_color=7 # white/light grey
muted_color=7 # white/light grey
text_color=7 # white
divider_color=7 # white
note_color=7 # white
main_color=6 # cyan
link_color=4 # blue
elif detect_light_terminal; then
dim_color=241 # dark grey - readable on white
muted_color=238 # darker grey for secondary text
text_color=236 # near-black for main descriptions
divider_color=250 # medium grey for dividers (visible on white)
note_color=243 # grey for notes
else
dim_color=245 # light grey - readable on dark
muted_color=250 # lighter grey for secondary text
text_color=255 # near-white for main descriptions
divider_color=245 # grey for dividers
note_color=245 # grey for notes
fi
# Store basic terminal detection result for use in safe_input
# Preserve env var if already set by user
if [[ -z "$BASIC_TERMINAL" ]]; then
if detect_basic_terminal; then
BASIC_TERMINAL=true
else
BASIC_TERMINAL=false
fi
fi
# Safe input wrapper - always uses read for reliability across all terminals
# Usage: result=$(safe_input "prompt" "default_value" [password])
safe_input() {
local prompt="$1"
local default="$2"
local is_password="$3"
local result
# Always use read - works on all terminals including serial consoles
if [[ "$is_password" == "password" ]]; then
read -r -s -p "${prompt}: " result
echo "" >&2 # newline after hidden input
elif [[ -n "$default" ]]; then
read -r -p "${prompt} [${default}]: " result
result="${result:-$default}"
else
read -r -p "${prompt}: " result
fi
# Strip control characters (serial consoles add CR etc)
result=$(printf '%s' "$result" | tr -d '\r')
echo "$result"
}
# Safe choose wrapper - uses gum on normal terminals, numbered menu on basic terminals
# Usage: result=$(safe_choose "option1" "option2" "option3")
safe_choose() {
local options=("$@")
local i result
if [[ "$BASIC_TERMINAL" != "true" ]]; then
# Normal terminal - use gum choose for nice interactive experience
result=$(gum choose --cursor.foreground "$main_color" "${options[@]}")
echo "$result"
return 0
fi
# Basic terminal - use numbered menu
echo "" >&2
for i in "${!options[@]}"; do
echo " $((i+1))) ${options[$i]}" >&2
done
echo "" >&2
while true; do
read -r -p "Choose [1-${#options[@]}]: " result
# Strip whitespace and control characters (serial consoles add CR etc)
result=$(printf '%s' "$result" | tr -d '[:space:][:cntrl:]')
if [[ "$result" =~ ^[0-9]+$ ]] && [ "$result" -ge 1 ] && [ "$result" -le "${#options[@]}" ]; then
echo "${options[$((result-1))]}"
return 0
fi
echo "Invalid. Enter 1-${#options[@]}" >&2
done
}
# Safe confirm wrapper - uses numbered menu on basic terminals (gum toggle doesn't work well)
# Usage: if safe_confirm "Are you sure?"; then ...
safe_confirm() {
local prompt="${1:-Continue?}"
local yes_text="${2:-Yes}"
local no_text="${3:-No}"
local result
if [[ "$BASIC_TERMINAL" == "true" ]]; then
# Use numbered menu for basic terminals (same as safe_choose)
echo "" >&2
echo "$prompt" >&2
echo " 1) $yes_text" >&2
echo " 2) $no_text" >&2
echo "" >&2
while true; do
read -r -p "Choose [1-2]: " result
result=$(printf '%s' "$result" | tr -d '[:space:][:cntrl:]')
case "$result" in
1) return 0 ;; # Yes
2) return 1 ;; # No
*) echo "Invalid. Enter 1 or 2" >&2 ;;
esac
done
else
gum confirm --prompt.foreground "${main_color}" "$prompt"
fi
}
#
# EARLY DEPENDENCY CHECKS - must run before any gum usage
#
# check if a command exists
command_exists() {
command -v "$1" >/dev/null 2>&1
}
# Check if sudo is available and user can use it
# Returns 0 if sudo works, 1 otherwise
can_sudo() {
# Check if sudo exists
if ! command_exists sudo; then
return 1
fi
# Check if we can actually use sudo (might prompt for password)
# Use -n to avoid prompting - if it fails, sudo needs password
if sudo -n true 2>/dev/null; then
return 0
fi
# sudo exists but needs password - still return success but warn user
return 0
}
# Run a command with sudo if available, otherwise warn and try without
# Usage: run_with_sudo command [args...]
run_with_sudo() {
if can_sudo; then
sudo "$@"
else
echo "WARNING: sudo not available. Trying without elevated privileges..."
"$@"
fi
}
# Get system architecture for binary downloads
get_arch() {
local arch
arch=$(uname -m)
case "$arch" in
x86_64|amd64) echo "x86_64" ;;
arm64|aarch64) echo "arm64" ;;
armv7l) echo "armv7" ;;
*) echo "$arch" ;;
esac
}
# Get OS name for binary downloads
get_os() {
case "$(uname -s)" in
Darwin) echo "Darwin" ;;
Linux) echo "Linux" ;;
MINGW*|MSYS*|CYGWIN*) echo "Windows" ;;
*) echo "$(uname -s)" ;;
esac
}
# Download gum binary directly from GitHub releases (no package manager needed)
install_gum_binary() {
local version="0.14.5"
local os arch url tmpdir
os=$(get_os)
arch=$(get_arch)
echo "Downloading gum v${version} for ${os}/${arch}..."
# Determine download URL
local ext="tar.gz"
[[ "$os" == "Windows" ]] && ext="zip"
url="https://github.com/charmbracelet/gum/releases/download/v${version}/gum_${version}_${os}_${arch}.${ext}"
tmpdir=$(mktemp -d)
cd "$tmpdir" || return 1
if ! curl -fsSL -o "gum.${ext}" "$url"; then
echo "Failed to download gum from $url"
rm -rf "$tmpdir"
return 1
fi
# Extract
if [[ "$ext" == "zip" ]]; then
unzip -q "gum.${ext}"
else
tar -xzf "gum.${ext}"
fi
# Install to user bin directory
local install_dir="$HOME/.local/bin"
mkdir -p "$install_dir"
# Find and copy the binary
if [[ -f "gum" ]]; then
cp gum "$install_dir/"
elif [[ -f "gum_${version}_${os}_${arch}/gum" ]]; then
cp "gum_${version}_${os}_${arch}/gum" "$install_dir/"
else
# Try to find it
local gum_bin
gum_bin=$(find . -name "gum" -type f | head -1)
if [[ -n "$gum_bin" ]]; then
cp "$gum_bin" "$install_dir/"
else
echo "Could not find gum binary in downloaded archive"
rm -rf "$tmpdir"
return 1
fi
fi
chmod +x "$install_dir/gum"
rm -rf "$tmpdir"
# Add to PATH for this session if not already there
if [[ ":$PATH:" != *":$install_dir:"* ]]; then
export PATH="$install_dir:$PATH"
fi
echo "gum installed to $install_dir/gum"
echo "NOTE: Add $install_dir to your PATH permanently by adding this to your ~/.bashrc or ~/.zshrc:"
echo " export PATH=\"\$HOME/.local/bin:\$PATH\""
return 0
}
# Install gum using Go
install_gum_go() {
echo "Installing gum using Go..."
go install github.com/charmbracelet/gum@latest
}
# Install gum based on OS and available tools
install_gum() {
# Try direct binary download first (most reliable, no dependencies)
if install_gum_binary; then
return 0
fi
# Fallback: Try Go if available
if command_exists go; then
if install_gum_go; then
return 0
fi
fi
# Fallback: Try package managers
case "$(uname -s)" in
Darwin)
if command_exists brew; then
echo "Installing gum using Homebrew..."
brew install gum && return 0
fi
;;
Linux)
if command_exists apt-get; then
echo "Installing gum on Ubuntu/Debian..."
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://repo.charm.sh/apt/gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/charm.gpg
echo "deb [signed-by=/etc/apt/keyrings/charm.gpg] https://repo.charm.sh/apt/ * *" | sudo tee /etc/apt/sources.list.d/charm.list
sudo apt update && sudo apt install -y gum && return 0
elif command_exists pacman; then
echo "Installing gum using pacman..."
sudo pacman -S --noconfirm gum && return 0
fi
;;
esac
echo "=========================================="
echo "ERROR: Failed to install gum automatically"
echo "=========================================="
echo "Please install gum manually:"
echo " https://github.com/charmbracelet/gum#installation"
echo ""
echo "Quick options:"
echo " Mac: brew install gum"
echo " Linux: See https://github.com/charmbracelet/gum#linux"
echo "=========================================="
exit 1
}
# Download jq binary directly
install_jq_binary() {
local version="1.7.1"
local os arch url
os=$(get_os)
arch=$(get_arch)
echo "Downloading jq v${version} for ${os}/${arch}..."
# jq uses different naming convention
local jq_os jq_arch
case "$os" in
Darwin) jq_os="macos" ;;
Linux) jq_os="linux" ;;
Windows) jq_os="windows" ;;
*) jq_os="$os" ;;
esac
case "$arch" in
x86_64) jq_arch="amd64" ;;
arm64) jq_arch="arm64" ;;
*) jq_arch="$arch" ;;
esac
local ext=""
[[ "$os" == "Windows" ]] && ext=".exe"
url="https://github.com/jqlang/jq/releases/download/jq-${version}/jq-${jq_os}-${jq_arch}${ext}"
local install_dir="$HOME/.local/bin"
mkdir -p "$install_dir"
if curl -fsSL -o "$install_dir/jq" "$url"; then
chmod +x "$install_dir/jq"
if [[ ":$PATH:" != *":$install_dir:"* ]]; then
export PATH="$install_dir:$PATH"
fi
echo "jq installed to $install_dir/jq"
return 0
else
echo "Failed to download jq"
return 1
fi
}
# Install jq
install_jq() {
# Try direct binary download first
if install_jq_binary; then
return 0
fi
# Fallback to package managers
case "$(uname -s)" in
Linux)
if command_exists apt-get; then
echo "Installing jq with apt-get..."
sudo apt-get update && sudo apt-get install -y jq && return 0
elif command_exists yum; then
sudo yum install -y jq && return 0
elif command_exists dnf; then
sudo dnf install -y jq && return 0
elif command_exists pacman; then
sudo pacman -S --noconfirm jq && return 0
fi
;;
Darwin)
if command_exists brew; then
brew install jq && return 0
fi
;;
esac
echo "Failed to install jq. Please install manually: https://jqlang.github.io/jq/download/"
exit 1
}
# Install Docker
install_docker() {
case "$(uname -s)" in
Linux)
echo "Installing Docker using official convenience script..."
echo "(This requires sudo access)"
if curl -fsSL https://get.docker.com | sh; then
# Add current user to docker group
sudo usermod -aG docker "$USER" 2>/dev/null || true
echo ""
echo "Docker installed successfully!"
echo "NOTE: You may need to log out and back in for docker group permissions to take effect."
echo " Or run: newgrp docker"
return 0
else
echo "Docker installation failed"
return 1
fi
;;
Darwin)
echo "=========================================="
echo "Docker Desktop Required (Mac)"
echo "=========================================="
echo "Docker Desktop must be installed manually on Mac."
echo ""
echo "Download from: https://www.docker.com/products/docker-desktop/"
echo ""
echo "After installing, make sure Docker Desktop is running,"
echo "then run this script again."
echo "=========================================="
exit 1
;;
MINGW*|MSYS*|CYGWIN*)
echo "=========================================="
echo "Docker Desktop Required (Windows)"
echo "=========================================="
echo "For Windows, please install Docker Desktop:"
echo " https://www.docker.com/products/docker-desktop/"
echo ""
echo "Or if using WSL2, ensure Docker Desktop is configured"
echo "to integrate with your WSL distribution."
echo "=========================================="
exit 1
;;
*)
echo "Unsupported OS for automatic Docker installation."
echo "Please install Docker manually: https://docs.docker.com/engine/install/"
exit 1
;;
esac
}
# Check for NVIDIA GPU and container toolkit
# Shows instructions if toolkit is missing - user installs manually and re-runs bootstrap
check_nvidia_toolkit() {
# Only relevant on Linux
[[ "$OS_TYPE" != "Linux" ]] && return 0
# Check if nvidia-smi exists (NVIDIA drivers installed)
if ! command_exists nvidia-smi; then
# No NVIDIA GPU or drivers - continue silently in CPU-only mode
log_line "No NVIDIA GPU detected, continuing in CPU-only mode"
return 0
fi
# GPU detected - check if container toolkit is installed
local toolkit_installed=false
if command_exists nvidia-container-runtime; then
toolkit_installed=true
elif docker info 2>/dev/null | grep -qi "nvidia"; then
toolkit_installed=true
fi
if [ "$toolkit_installed" = true ]; then
log_line "NVIDIA GPU and container toolkit detected"
echo "NVIDIA GPU detected with container toolkit installed"
return 0
fi
# GPU detected but toolkit missing - show instructions
echo ""
echo "════════════════════════════════════════════════════════════════"
echo " NVIDIA GPU Detected - Container Toolkit Required"
echo "════════════════════════════════════════════════════════════════"
echo ""
echo "Your system has an NVIDIA GPU, but the NVIDIA Container Toolkit"
echo "is not installed. This toolkit is required for GPU acceleration."
echo ""
echo "To install the NVIDIA Container Toolkit:"
echo ""
if command_exists apt-get; then
echo " # Add the NVIDIA repository"
echo " curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey \\"
echo " | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg"
echo ""
echo " curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list \\"
echo " | sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' \\"
echo " | sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list"
echo ""
echo " # Install the toolkit"
echo " sudo apt-get update"
echo " sudo apt-get install -y nvidia-container-toolkit"
echo ""
echo " # Configure Docker and restart"
echo " sudo nvidia-ctk runtime configure --runtime=docker"
echo " sudo systemctl restart docker"
elif command_exists dnf; then
echo " # Add the NVIDIA repository"
echo " curl -s -L https://nvidia.github.io/libnvidia-container/stable/rpm/nvidia-container-toolkit.repo \\"
echo " | sudo tee /etc/yum.repos.d/nvidia-container-toolkit.repo"
echo ""
echo " # Install the toolkit"
echo " sudo dnf install -y nvidia-container-toolkit"
echo ""
echo " # Configure Docker and restart"
echo " sudo nvidia-ctk runtime configure --runtime=docker"
echo " sudo systemctl restart docker"
elif command_exists yum; then
echo " # Add the NVIDIA repository"
echo " curl -s -L https://nvidia.github.io/libnvidia-container/stable/rpm/nvidia-container-toolkit.repo \\"
echo " | sudo tee /etc/yum.repos.d/nvidia-container-toolkit.repo"
echo ""
echo " # Install the toolkit"
echo " sudo yum install -y nvidia-container-toolkit"
echo ""
echo " # Configure Docker and restart"
echo " sudo nvidia-ctk runtime configure --runtime=docker"
echo " sudo systemctl restart docker"
else
echo " See: https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html"
fi
echo ""
echo "════════════════════════════════════════════════════════════════"
echo ""
echo "Options:"
echo " 1) Exit now, install the toolkit, then re-run bootstrap"
echo " 2) Continue without GPU (CPU-only mode)"
echo ""
read -p "Continue without GPU? [y/N] " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
echo ""
echo "Continuing in CPU-only mode..."
echo "You can install the toolkit later and re-run bootstrap for GPU support."
log_line "User chose to continue without GPU support"
return 0
else
echo ""
echo "Exiting. Please install the NVIDIA Container Toolkit and run bootstrap again."
log_line "User exited to install NVIDIA toolkit"
exit 0
fi
}
# Check if gum is installed, install if not
check_gum_installed() {
if ! command_exists gum; then
echo "gum not found. Installing..."
install_gum
fi
}
# Check if jq is installed, install if not
check_jq_installed() {
if ! command_exists jq; then
echo "jq not found. Installing..."
install_jq
fi
}
# Check if Docker is installed, install if not
check_docker_installed() {
if ! command_exists docker; then
echo "Docker not found."
install_docker
fi
# Verify Docker is running
if ! docker info >/dev/null 2>&1; then
echo ""
echo "WARNING: Docker is installed but not running or accessible."
echo ""
case "$(uname -s)" in
Darwin)
echo "Please start Docker Desktop and try again."
;;
Linux)
echo "Try one of these:"
echo " 1. Start Docker: sudo systemctl start docker"
echo " 2. Add yourself to docker group: sudo usermod -aG docker $USER"
echo " Then log out and back in."
;;
esac
exit 1
fi
}
# Check if curl is available (required for downloads)
check_curl_installed() {
if ! command_exists curl; then