forked from smixs/iva-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbootstrap.sh
More file actions
executable file
·1472 lines (1372 loc) · 56.9 KB
/
Copy pathbootstrap.sh
File metadata and controls
executable file
·1472 lines (1372 loc) · 56.9 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
#
# Prepare a fresh VPS for Iva (a personal long-term-memory agent) with one command,
# as root, on Ubuntu 22.04/24.04 or Debian 12:
#
# bash <(curl -fsSL https://raw.githubusercontent.com/smixs/iva/main/bootstrap.sh)
#
# What it does, in this order: sets the timezone, updates the system, installs the
# packages install.sh expects (git, gh, python3, ffmpeg, pandoc, poppler), creates a
# sudo user with systemd lingering enabled, turns on a firewall that allows SSH only,
# starts fail2ban, enables unattended security upgrades, and hardens sshd LAST — with
# a reload, so the session you are typing in is never dropped. It ends with the two
# commands that finish the install — and, when the upgrade brought a new kernel, with
# a reboot, because install.sh refuses to run while one is pending.
#
# It never asks for an SSH key: you log in as the new user with the password you set
# here, and hardening stops at PermitRootLogin no. Headless runs can still authorize a
# key with IVA_PUBKEY, and only then may IVA_DISABLE_PASSWORD_AUTH turn passwords off.
#
# Every step is detect-then-skip: running it twice changes nothing and exits 0.
# This script installs no agent code. Iva itself is installed by install.sh, from the
# new user's own shell — the shell tool runs as whoever installed it, never as root.
#
# Flags:
# --non-interactive never ask anything; read the answers from the environment
# -h, --help show this help and exit
#
# Environment (required in non-interactive mode):
# IVA_USER login to create or reuse, e.g. iva
# IVA_PASS password, required only when the user does not exist
# IVA_PUBKEY optional SSH public key to authorize
# IVA_TZ optional IANA timezone, e.g. Europe/Berlin
# IVA_DISABLE_PASSWORD_AUTH optional true/false; default true with a key, false without
# IVA_REBOOT optional true/false; reboot when the upgrade brought a
# new kernel. Default false — never reboot silently.
#
# Log: /var/log/iva-bootstrap.log (mode 600).
set -Eeuo pipefail
# ── Constants ────────────────────────────────────────────────────────────────
# gum is pinned and checksum-verified: it only paints the interface, so a bad
# download must never become a silent binary install. Mismatch → plain text mode.
GUM_VERSION="0.17.0"
GUM_SHA256_X86_64="69ee169bd6387331928864e94d47ed01ef649fbfe875baed1bbf27b5377a6fdb"
GUM_SHA256_ARM64="b0b9ed95cbf7c8b7073f17b9591811f5c001e33c7cfd066ca83ce8a07c576f9c"
RAW_BASE="https://raw.githubusercontent.com/smixs/iva/main"
LOG_FILE="/var/log/iva-bootstrap.log"
SSHD_MAIN_CONFIG="/etc/ssh/sshd_config"
SSHD_DROPIN_DIR="/etc/ssh/sshd_config.d"
# 00- on purpose. sshd keeps the FIRST value it reads for a keyword, and cloud images
# ship 50-cloud-init.conf with `PasswordAuthentication yes`. A 99- file would lose.
SSHD_DROPIN="/etc/ssh/sshd_config.d/00-iva-hardening.conf"
FAIL2BAN_JAIL="/etc/fail2ban/jail.local"
AUTO_UPGRADES_CONF="/etc/apt/apt.conf.d/20auto-upgrades"
# apt leaves this behind when an upgraded package (kernel, glibc, dbus) needs a reboot.
REBOOT_REQUIRED_FLAG="/var/run/reboot-required"
MARKER="# managed by the iva VPS bootstrap"
# iva palette (see deploy/iva-tree.ans) — one source for both the gum flags and the raw ANSI fallbacks
C_PRIMARY=113 # leaf green
C_ACCENT=71 # moss
C_OK=84 # green
C_WARN=214 # amber
C_ERR=196 # red
C_MUTED=245 # grey
PACKAGES="sudo curl ca-certificates git python3 ffmpeg pandoc poppler-utils unattended-upgrades fail2ban ufw openssh-server"
# ── Mutable state ────────────────────────────────────────────────────────────
UI_MODE="plain" # gum | plain | none
NON_INTERACTIVE=false
GUM_SUPPORTED=true
CURRENT_STEP="startup"
SPINNER_PID=""
STEP_NO=0
STEP_TOTAL=8
TARGET_USER=""
TARGET_PASS=""
CREATE_USER=false
PUBKEY=""
DISABLE_PASSWORD_AUTH=false
TIMEZONE_CHOICE=""
SSH_PORT=22
c_blue=""; c_green=""; c_yellow=""; c_red=""; c_bold=""; c_reset=""
# ─────────────────────────────────────────────────────────────────────────────
# Output primitives (same shape as install.sh, so the two scripts read alike)
# ─────────────────────────────────────────────────────────────────────────────
setup_colors() {
if [ -n "${NO_COLOR:-}" ] || [ "${TERM:-}" = dumb ] || [ ! -t 1 ]; then
c_blue=""; c_green=""; c_yellow=""; c_red=""; c_bold=""; c_reset=""
else
c_blue=$'\033[38;5;'"${C_ACCENT}"'m'
c_green=$'\033[38;5;'"${C_OK}"'m'
c_yellow=$'\033[38;5;'"${C_WARN}"'m'
c_red=$'\033[38;5;'"${C_ERR}"'m'
c_bold=$'\033[1m'
c_reset=$'\033[0m'
fi
}
step() { echo "${c_blue}▸ $*${c_reset}"; }
ok() { echo "${c_green}✓ $*${c_reset}"; }
warn() { echo "${c_yellow}! $*${c_reset}"; }
die() { stop_spinner; echo "${c_red}✗ $*${c_reset}" >&2; exit 1; }
# 2>/dev/null comes FIRST on purpose: a failing redirect is reported on the fd 2 that
# is current when it fails, so silencing it afterwards would be too late.
log() { printf '[%s] %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$*" 2>/dev/null >>"$LOG_FILE" || true; }
init_log() {
if ! : 2>/dev/null >"$LOG_FILE"; then
LOG_FILE="${TMPDIR:-/tmp}/iva-bootstrap.log"
: 2>/dev/null >"$LOG_FILE" || true
fi
chmod 600 "$LOG_FILE" 2>/dev/null || true
log "bootstrap started: $(uname -srm), uid $(id -u), ui=$UI_MODE"
}
# ── Compact progress. Long work prints to the log only; the screen gets a spinner ──
spinner_enabled() {
[ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-}" != dumb ]
}
stop_spinner() {
if [ -n "$SPINNER_PID" ]; then
kill "$SPINNER_PID" 2>/dev/null || true
wait "$SPINNER_PID" 2>/dev/null || true
SPINNER_PID=""
printf '\r\033[2K\033[?25h'
fi
}
start_spinner() {
local label="$1"
if ! spinner_enabled; then
echo "◇ $label"
return
fi
printf '\033[?25l'
(
local frames=('◇' '◈' '◆' '◈') i=0
while :; do
printf '\r\033[2K%s %s' "${frames[$i]}" "$label"
i=$(( (i + 1) % 4 ))
sleep 0.09
done
) &
SPINNER_PID=$!
}
# run_stage LABEL SUCCESS COMMAND [ARG...] — runs the command with every byte of its
# output redirected into the log, behind a spinner. gum only draws; failures are
# handled here so the reporting is identical in both modes.
run_stage() {
local label="$1" success="$2"
shift 2
CURRENT_STEP="$label"
log "stage: $label"
local rc=0
if [ "$UI_MODE" = gum ] && spinner_enabled; then
# gum spin owns the terminal, so the work redirects its own output inside the
# child instead of us redirecting gum. $1 is the log path, passed as an argument.
# shellcheck disable=SC2016 # the child must expand $1/$@, not this shell
gum spin --spinner dot --spinner.foreground "$C_PRIMARY" --title "$label" -- \
bash -c 'exec >>"$1" 2>&1; shift; "$@"' iva-bootstrap "$LOG_FILE" "$@" || rc=$?
else
start_spinner "$label"
"$@" >>"$LOG_FILE" 2>&1 || rc=$?
stop_spinner
fi
if [ "$rc" -eq 0 ]; then
ok "$success"
return 0
fi
warn "Failed: $label"
tail -n 12 "$LOG_FILE" >&2 || true
echo "Full log: $LOG_FILE" >&2
return "$rc"
}
# run_sh LABEL SUCCESS 'shell code' — same, for anything that needs a pipe or &&.
run_sh() { run_stage "$1" "$2" bash -c "$3"; }
# ── Loud error handler: no silent exits from set -e ──────────────────────────
on_err() {
local rc=$?
stop_spinner
echo >&2
echo "${c_red}✗ Bootstrap stopped (exit $rc) during: ${CURRENT_STEP}${c_reset}" >&2
echo "${c_red} Failing command: ${BASH_COMMAND}${c_reset}" >&2
if [ -f "$LOG_FILE" ]; then
echo "${c_yellow} Last log lines:${c_reset}" >&2
tail -n 12 "$LOG_FILE" >&2 || true
echo "${c_yellow} Full log: $LOG_FILE${c_reset}" >&2
fi
echo "${c_yellow} Your current SSH session is untouched: sshd hardening is the last step" >&2
echo "${c_yellow} and it never drops open sessions. Fix the cause and run this again.${c_reset}" >&2
}
usage() {
cat <<'USAGE'
Prepare a fresh Ubuntu/Debian VPS for Iva. Run as root:
bash <(curl -fsSL https://raw.githubusercontent.com/smixs/iva/main/bootstrap.sh)
It sets the timezone, updates the system, installs Iva's system packages, creates a
sudo user with lingering enabled, enables a SSH-only firewall, fail2ban and unattended
security upgrades, and hardens sshd last (reload, never a restart). Re-running it is
safe: every step is detect-then-skip.
Interactively it asks three things: the login, its password, and the timezone. It does
not ask for an SSH key — you log in with that password, and hardening stops at
PermitRootLogin no. Headless runs can authorize a key with IVA_PUBKEY.
Flags:
--non-interactive never ask anything; read the answers from the environment
-h, --help show this help and exit
Environment (required in non-interactive mode):
IVA_USER login to create or reuse, e.g. iva
IVA_PASS password, required only when the user does not exist
IVA_PUBKEY optional SSH public key to authorize
IVA_TZ optional IANA timezone, e.g. Europe/Berlin
IVA_DISABLE_PASSWORD_AUTH optional true/false; default true with a key, false without
IVA_REBOOT optional true/false; reboot when the upgrade brought a new
kernel. Default false — never reboot silently. Interactive
runs are asked instead.
Example:
IVA_USER=iva IVA_PASS='...' IVA_PUBKEY="$(cat ~/.ssh/id_ed25519.pub)" \
bash bootstrap.sh --non-interactive
Log: /var/log/iva-bootstrap.log
USAGE
}
# ─────────────────────────────────────────────────────────────────────────────
# 0. Preflight: arguments, root, distribution, architecture
# ─────────────────────────────────────────────────────────────────────────────
parse_args() {
while [ $# -gt 0 ]; do
case "$1" in
--non-interactive) NON_INTERACTIVE=true ;;
-h|--help) usage; exit 0 ;;
*) warn "unknown flag: $1 (ignoring)" ;;
esac
shift
done
}
os_release_field() {
awk -F= -v key="$1" '$1 == key { gsub(/^"|"$/, "", $2); print $2; exit }' /etc/os-release 2>/dev/null || true
}
preflight() {
CURRENT_STEP="preflight checks"
parse_args "$@"
if [ "$(id -u)" != 0 ]; then
die "run this as root — it creates a user, installs packages and configures the firewall. Log in as root, then re-run."
fi
local id_field id_like_field
id_field="$(os_release_field ID)"
id_like_field="$(os_release_field ID_LIKE)"
case "$id_field" in
ubuntu|debian) : ;;
*)
case " $id_like_field " in
*debian*) : ;;
*) die "this bootstrap targets Ubuntu 22.04/24.04 and Debian 12 (found ID='${id_field:-unknown}'). Install the packages by hand, then run install.sh." ;;
esac
;;
esac
case "$(uname -m)" in
x86_64|aarch64) : ;;
*)
GUM_SUPPORTED=false
warn "architecture $(uname -m) has no prebuilt gum — using the plain text interface"
;;
esac
if [ "$NON_INTERACTIVE" = true ]; then UI_MODE=none; else UI_MODE=plain; fi
}
have_systemd() { [ -d /run/systemd/system ]; }
# ─────────────────────────────────────────────────────────────────────────────
# 1. gum — the terminal UI toolkit. Optional by design: any failure downgrades
# the interface to plain text and the bootstrap keeps going.
# ─────────────────────────────────────────────────────────────────────────────
install_gum() {
CURRENT_STEP="installing the terminal UI toolkit"
if [ "$UI_MODE" = none ]; then
return 0
fi
# No termcap, no full-screen widgets: gum's text input panics outright on TERM=dumb
# (and an empty TERM is no better). setup_colors and spinner_enabled already bail on
# dumb — the gum mode was the one path that did not. Do not even download it.
case "${TERM:-}" in
''|dumb) return 0 ;;
esac
if command -v gum >/dev/null 2>&1; then
UI_MODE=gum
return 0
fi
if [ "$GUM_SUPPORTED" != true ]; then
return 0
fi
if ! command -v tar >/dev/null 2>&1 || ! command -v sha256sum >/dev/null 2>&1; then
warn "tar or sha256sum missing — using the plain text interface"
return 0
fi
local asset expected
case "$(uname -m)" in
x86_64) asset="gum_${GUM_VERSION}_Linux_x86_64.tar.gz"; expected="$GUM_SHA256_X86_64" ;;
aarch64) asset="gum_${GUM_VERSION}_Linux_arm64.tar.gz"; expected="$GUM_SHA256_ARM64" ;;
*) return 0 ;;
esac
local tmp
if ! tmp="$(mktemp -d 2>/dev/null)"; then
warn "couldn't create a temp directory — using the plain text interface"
return 0
fi
local url="https://github.com/charmbracelet/gum/releases/download/v${GUM_VERSION}/${asset}"
start_spinner "Fetching the terminal UI toolkit"
if ! curl -fsSL --connect-timeout 10 --max-time 120 --retry 2 -o "$tmp/$asset" "$url" >>"$LOG_FILE" 2>&1; then
stop_spinner
rm -rf "$tmp"
warn "couldn't download gum — using the plain text interface"
return 0
fi
# Checksum first, unpack second: nothing unverified is ever extracted or installed.
if ! printf '%s %s\n' "$expected" "$tmp/$asset" | sha256sum -c --status - >>"$LOG_FILE" 2>&1; then
stop_spinner
rm -rf "$tmp"
warn "gum checksum mismatch — refusing to install it, using the plain text interface"
return 0
fi
if ! tar -xzf "$tmp/$asset" -C "$tmp" >>"$LOG_FILE" 2>&1; then
stop_spinner
rm -rf "$tmp"
warn "couldn't unpack gum — using the plain text interface"
return 0
fi
# The binary sits in a versioned subdirectory inside the archive; find it, don't guess.
# `|| binary=""`: head closing the pipe early would otherwise make pipefail abort here.
local binary
binary="$(find "$tmp" -type f -name gum 2>/dev/null | head -n1)" || binary=""
if [ -z "$binary" ] || ! install -m 755 "$binary" /usr/local/bin/gum >>"$LOG_FILE" 2>&1; then
stop_spinner
rm -rf "$tmp"
warn "couldn't install gum — using the plain text interface"
return 0
fi
rm -rf "$tmp"
stop_spinner
if command -v gum >/dev/null 2>&1; then
UI_MODE=gum
log "gum ${GUM_VERSION} installed in /usr/local/bin"
else
warn "gum is not on PATH — using the plain text interface"
fi
}
# ─────────────────────────────────────────────────────────────────────────────
# 2. Banner. The art is stored in ASCII (# = full block, _ = lower half) so the
# per-character walk is byte-safe in any locale; the block glyphs are emitted
# at print time. Colour is a 24-bit gradient across the columns.
# ─────────────────────────────────────────────────────────────────────────────
show_banner() {
if [ "$UI_MODE" != gum ] || [ -n "${NO_COLOR:-}" ] || [ ! -t 1 ]; then
return 0
fi
local letter_i=("#######" " ### " " ### " " ### " " ### " "#######")
local letter_v=("### ###" "### ###" "### ###" " ### ### " " ##### " " ### ")
local letter_a=(" _#####_ " "### ###" "### ###" "#########" "### ###" "### ###")
# Palette derived from the canonical tree art in deploy/iva-tree.ans (earthy greens,
# mean RGB 103,121,82, amber only in the highlights): forest green #387630 → light
# leaf #B2D66A, lifted in brightness so the letters stay readable on a dark terminal.
local r0=56 g0=118 b0=48 r1=178 g1=214 b1=106
local row line len i ch glyph r g b span
printf '\n'
for row in 0 1 2 3 4 5; do
line="${letter_i[$row]} ${letter_v[$row]} ${letter_a[$row]}"
len=${#line}
span=$(( len > 1 ? len - 1 : 1 ))
printf ' '
for (( i = 0; i < len; i++ )); do
ch="${line:i:1}"
case "$ch" in
'#') glyph='█' ;;
'_') glyph='▄' ;;
'~') glyph='▀' ;;
*) printf ' '; continue ;;
esac
r=$(( r0 + (r1 - r0) * i / span ))
g=$(( g0 + (g1 - g0) * i / span ))
b=$(( b0 + (b1 - b0) * i / span ))
printf '\033[38;2;%d;%d;%dm%s' "$r" "$g" "$b" "$glyph"
done
printf '\033[0m\n'
sleep 0.04
done
printf '\n'
gum style --foreground "$C_ACCENT" --italic --margin "0 2" \
"VPS bootstrap for iva — your personal long-term-memory agent" 2>/dev/null || true
printf '\n'
}
section() {
STEP_NO=$(( STEP_NO + 1 ))
local title="[$STEP_NO/$STEP_TOTAL] $1"
CURRENT_STEP="$1"
log "=== $title ==="
if [ "$UI_MODE" = gum ] && [ -t 1 ]; then
gum style --border rounded --border-foreground "$C_ACCENT" --padding "0 2" --margin "1 0" "$title" 2>/dev/null \
|| { echo; echo "${c_bold}${c_blue}── $title ──${c_reset}"; }
else
echo
echo "${c_bold}${c_blue}── $title ──${c_reset}"
fi
}
# ─────────────────────────────────────────────────────────────────────────────
# 3. UI abstraction: gum | plain | none. Every question goes through these four.
# ─────────────────────────────────────────────────────────────────────────────
read_tty() {
local __name="$1" __answer=""
if (: </dev/tty) 2>/dev/null; then
IFS= read -r __answer </dev/tty || __answer=""
else
IFS= read -r __answer || __answer=""
fi
printf -v "$__name" '%s' "$__answer"
}
read_tty_secret() {
local __name="$1" __answer=""
if (: </dev/tty) 2>/dev/null; then
IFS= read -rs __answer </dev/tty || __answer=""
else
IFS= read -rs __answer || __answer=""
fi
printf -v "$__name" '%s' "$__answer"
}
ui_ask() {
if [ "$UI_MODE" = gum ]; then
gum style --foreground "$C_ACCENT" --bold "$*" 2>/dev/null || echo "${c_bold}${c_blue}$*${c_reset}"
else
echo
echo "${c_bold}${c_blue}$*${c_reset}"
fi
}
ui_note() {
if [ "$UI_MODE" = gum ]; then
gum style --foreground "$C_MUTED" --italic "$*" 2>/dev/null || echo " $*"
else
echo " $*"
fi
}
# ui_gum_failed RC — true when gum itself broke, false when the user aborted.
# 130 is Esc or Ctrl-C: the user's own choice, honour it. Any other non-zero status
# means the widget died on us (gum 0.17 panics outright on some terminals), so drop to
# plain prompts for the rest of the run and let the caller re-ask the same question.
# Never accept the empty string a crashed widget returns — that is how a wrong username
# or an unenterable password slips through unnoticed.
# Capture the status with `|| rc=$?`, never `if ! v="$(gum …)"` — `!` rewrites $? to 0.
ui_gum_failed() {
local rc="$1"
if [ "$rc" -eq 130 ]; then
return 1
fi
if [ "$UI_MODE" = gum ]; then
warn "the fancy interface failed — switching to plain prompts"
UI_MODE=plain
fi
return 0
}
# ui_input VAR "prompt" "placeholder"
ui_input() {
local __name="$1" __prompt="$2" __placeholder="${3:-}" __value="" __rc=0
case "$UI_MODE" in
none)
__value=""
;;
gum)
ui_ask "$__prompt"
__value="$(gum input --prompt '> ' --prompt.foreground "$C_PRIMARY" \
--cursor.foreground "$C_PRIMARY" --placeholder "$__placeholder")" || __rc=$?
if [ "$__rc" -ne 0 ]; then
__value=""
if ui_gum_failed "$__rc"; then
# Now in plain mode: ask the very same question again instead of
# silently handing the caller an empty answer.
ui_input "$__name" "$__prompt" "$__placeholder"
return 0
fi
fi
;;
*)
ui_ask "$__prompt"
if [ -n "$__placeholder" ]; then
printf '> (for example: %s) ' "$__placeholder"
else
printf '> '
fi
read_tty __value
;;
esac
printf -v "$__name" '%s' "$__value"
}
# ui_password VAR "prompt" — asks twice, requires at least 8 characters
ui_password() {
local __name="$1" __prompt="$2" first="" second="" attempts=0 __rc=0
if [ "$UI_MODE" = none ]; then
printf -v "$__name" '%s' ""
return 0
fi
while :; do
attempts=$(( attempts + 1 ))
if [ "$attempts" -gt 5 ]; then
die "too many failed password attempts"
fi
ui_ask "$__prompt"
if [ "$UI_MODE" = gum ]; then
__rc=0
first="$(gum input --password --prompt '> ' --prompt.foreground "$C_PRIMARY" \
--cursor.foreground "$C_PRIMARY" --placeholder 'at least 8 characters')" || __rc=$?
if [ "$__rc" -ne 0 ]; then
first=""
if ui_gum_failed "$__rc"; then
# A broken widget is not a failed attempt: restart the budget and ask
# again in plain mode, rather than looping on "too short" until we die.
attempts=0
continue
fi
fi
else
printf '> '
read_tty_secret first
echo
fi
if [ "${#first}" -lt 8 ]; then
warn "too short — use at least 8 characters"
continue
fi
ui_ask "Repeat the password"
if [ "$UI_MODE" = gum ]; then
__rc=0
second="$(gum input --password --prompt '> ' --prompt.foreground "$C_PRIMARY" \
--cursor.foreground "$C_PRIMARY" --placeholder 'the same one again')" || __rc=$?
if [ "$__rc" -ne 0 ]; then
second=""
if ui_gum_failed "$__rc"; then
attempts=0
continue
fi
fi
else
printf '> '
read_tty_secret second
echo
fi
if [ "$first" != "$second" ]; then
warn "the two entries differ — try again"
continue
fi
break
done
printf -v "$__name" '%s' "$first"
first=""
second=""
}
# ui_confirm "question" default → exit 0 for yes, 1 for no
ui_confirm() {
local question="$1" default="${2:-no}" answer="" gum_default=false suffix="[y/N]"
case "$default" in
[yY]*|1|true) gum_default=true; suffix="[Y/n]" ;;
*) gum_default=false; suffix="[y/N]" ;;
esac
case "$UI_MODE" in
none)
if [ "$gum_default" = true ]; then return 0; else return 1; fi
;;
gum)
# Deliberately no crash detection here: `gum confirm` answers "No" with status 1,
# which is indistinguishable from a crash, and guessing wrong would flip a real
# "No" into a re-ask. It does not need one — the first widget of the flow is
# always an input (the username), so a gum that is broken on this terminal has
# already degraded the whole run to plain prompts before any confirm runs.
if gum confirm --default="$gum_default" --affirmative "Yes" --negative "No" \
--selected.background "$C_PRIMARY" "$question"; then
return 0
fi
return 1
;;
*)
printf '%s %s ' "$question" "$suffix"
read_tty answer
answer="$(printf '%s' "$answer" | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]')"
if [ -z "$answer" ]; then
if [ "$gum_default" = true ]; then return 0; else return 1; fi
fi
case "$answer" in
y|yes) return 0 ;;
*) return 1 ;;
esac
;;
esac
}
# ui_filter VAR "placeholder" < list-on-stdin
# Redirection, never a pipe: a pipe would run this in a subshell and lose the answer.
ui_filter() {
local __name="$1" __placeholder="${2:-}" __value="" __line="" __count=0 __choice="" __item=""
local __list="" __rc=0
local __items=()
if [ "$UI_MODE" = none ]; then
printf -v "$__name" '%s' ""
return 0
fi
# Buffer the list BEFORE gum sees it. gum consumes stdin, so if it dies mid-read the
# plain fallback would have an empty or truncated list left to offer.
while IFS= read -r __line; do
if [ -n "$__line" ]; then
__items+=("$__line")
__list+="$__line"$'\n'
fi
done
__count="${#__items[@]}"
if [ "$__count" -eq 0 ]; then
printf -v "$__name" '%s' ""
return 0
fi
if [ "$UI_MODE" = gum ]; then
__value="$(gum filter --height 12 --placeholder "$__placeholder" --prompt '> ' \
--prompt.foreground "$C_PRIMARY" --indicator.foreground "$C_PRIMARY" \
<<<"${__list%$'\n'}")" || __rc=$?
if [ "$__rc" -eq 0 ]; then
printf -v "$__name" '%s' "$__value"
return 0
fi
__value=""
if ! ui_gum_failed "$__rc"; then
# The user aborted on purpose — hand back nothing, as before.
printf -v "$__name" '%s' ""
return 0
fi
# Degraded to plain: fall through and offer the buffered list instead.
fi
if [ "$__count" -gt 30 ]; then
# A numbered menu over hundreds of entries is unusable — ask for the exact value.
ui_note "$__count options — type the exact value (for example: $__placeholder)"
printf '> '
read_tty __value
__value="$(printf '%s' "$__value" | tr -d '[:space:]')"
local found=""
for __item in "${__items[@]}"; do
if [ "$__item" = "$__value" ]; then
found=yes
break
fi
done
if [ -z "$found" ]; then
warn "'$__value' is not in the list — skipping"
__value=""
fi
else
local index=1
for __item in "${__items[@]}"; do
printf ' %2d) %s\n' "$index" "$__item"
index=$(( index + 1 ))
done
printf '> pick a number: '
read_tty __choice
case "$__choice" in
''|*[!0-9]*) __value="" ;;
*)
if [ "$__choice" -ge 1 ] && [ "$__choice" -le "$__count" ]; then
__value="${__items[$(( __choice - 1 ))]}"
else
__value=""
fi
;;
esac
fi
printf -v "$__name" '%s' "$__value"
}
# ─────────────────────────────────────────────────────────────────────────────
# 4. Every question up front, before anything on the system changes.
# ─────────────────────────────────────────────────────────────────────────────
lowercase() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; }
valid_username() {
grep -qE '^[a-z][a-z0-9_-]{0,31}$' <<<"$1"
}
sanitize_pubkey() {
# Windows clipboards carry CRLF and people paste whole files, so: first line only,
# no carriage returns, no surrounding blanks. Pure parameter expansion — a pipeline
# here would put a SIGPIPE race between the script and `set -o pipefail`.
local key="${1%%$'\n'*}"
key="${key//$'\r'/}"
key="${key#"${key%%[![:space:]]*}"}"
key="${key%"${key##*[![:space:]]}"}"
printf '%s' "$key"
}
valid_pubkey() {
local key="$1"
if [ -z "$key" ]; then
return 1
fi
if command -v ssh-keygen >/dev/null 2>&1; then
ssh-keygen -l -f /dev/stdin <<<"$key" >/dev/null 2>&1
return $?
fi
grep -qE '^(ssh-(rsa|ed25519|dss)|ecdsa-sha2-nistp[0-9]+|sk-[a-z0-9@.-]+) [A-Za-z0-9+/]+=*( .*)?$' <<<"$key"
}
current_timezone() {
local tz=""
if command -v timedatectl >/dev/null 2>&1; then
tz="$(timedatectl show -p Timezone --value 2>/dev/null || true)"
fi
if [ -z "$tz" ] && [ -r /etc/timezone ]; then
tz="$(head -n1 /etc/timezone 2>/dev/null || true)"
fi
if [ -z "$tz" ] && [ -L /etc/localtime ]; then
tz="$(readlink /etc/localtime 2>/dev/null | sed 's#.*/zoneinfo/##' || true)"
fi
printf '%s' "${tz:-UTC}"
}
valid_timezone() {
[ -n "$1" ] && [ -f "/usr/share/zoneinfo/$1" ]
}
gather_input() {
CURRENT_STEP="collecting answers"
ask_username
ask_password
ask_pubkey
ask_timezone
}
ask_username() {
local candidate="" uid=""
while :; do
if [ "$UI_MODE" = none ]; then
candidate="${IVA_USER:-}"
if [ -z "$candidate" ]; then
die "IVA_USER is required without a terminal. Example:
IVA_USER=iva IVA_PASS='choose-a-strong-one' IVA_PUBKEY=\"\$(cat ~/.ssh/id_ed25519.pub)\" \\
bash bootstrap.sh --non-interactive"
fi
else
ui_note "Iva runs as this user, never as root — its shell tool inherits these permissions."
ui_input candidate "Login for the everyday sudo user" "iva"
candidate="$(printf '%s' "$candidate" | tr -d '[:space:]')"
if [ -z "$candidate" ]; then
candidate="iva"
fi
fi
if ! valid_username "$candidate"; then
if [ "$UI_MODE" = none ]; then
die "IVA_USER='$candidate' is not a valid login: start with a lowercase letter, then lowercase letters, digits, '_' or '-', 32 characters max."
fi
warn "'$candidate' is not a valid login: start with a lowercase letter, then lowercase letters, digits, '_' or '-', 32 characters max"
continue
fi
if id -u "$candidate" >/dev/null 2>&1; then
uid="$(id -u "$candidate")"
if [ "$uid" -lt 1000 ]; then
if [ "$UI_MODE" = none ]; then
die "'$candidate' is a system account (uid $uid) — pick another name"
fi
warn "'$candidate' is a system account (uid $uid) — pick another name"
continue
fi
if [ "$UI_MODE" = none ] || ui_confirm "User $candidate exists. Use it?" yes; then
TARGET_USER="$candidate"
CREATE_USER=false
return 0
fi
continue
fi
TARGET_USER="$candidate"
CREATE_USER=true
return 0
done
}
ask_password() {
if [ "$CREATE_USER" != true ]; then
return 0
fi
if [ "$UI_MODE" = none ]; then
TARGET_PASS="${IVA_PASS:-}"
if [ -z "$TARGET_PASS" ]; then
die "IVA_PASS is required: user '$TARGET_USER' does not exist yet and has to be created with a password."
fi
return 0
fi
ui_password TARGET_PASS "Password for $TARGET_USER (you will need it to log in)"
}
# Keys are a headless-only feature. The interactive flow deliberately asks nothing here:
# pasting a public key is a step too far for the people this bootstrap is written for, so
# they log in with the password they just set and hardening stops at PermitRootLogin no.
ask_pubkey() {
local candidate=""
if [ "$UI_MODE" != none ]; then
PUBKEY=""
DISABLE_PASSWORD_AUTH=false
return 0
fi
candidate="$(sanitize_pubkey "${IVA_PUBKEY:-}")"
if [ -n "$candidate" ]; then
if valid_pubkey "$candidate"; then
PUBKEY="$candidate"
else
warn "IVA_PUBKEY does not look like an SSH public key — continuing without it"
fi
fi
case "$(lowercase "${IVA_DISABLE_PASSWORD_AUTH:-}")" in
true|yes|1) DISABLE_PASSWORD_AUTH=true ;;
false|no|0) DISABLE_PASSWORD_AUTH=false ;;
*) if [ -n "$PUBKEY" ]; then DISABLE_PASSWORD_AUTH=true; else DISABLE_PASSWORD_AUTH=false; fi ;;
esac
# Without a key, disabling password logins locks everyone out. Never do it.
if [ -z "$PUBKEY" ]; then
DISABLE_PASSWORD_AUTH=false
fi
}
ask_timezone() {
local current list_file=""
current="$(current_timezone)"
if [ "$UI_MODE" = none ]; then
TIMEZONE_CHOICE="${IVA_TZ:-}"
if [ -n "$TIMEZONE_CHOICE" ] && ! valid_timezone "$TIMEZONE_CHOICE"; then
warn "IVA_TZ='$TIMEZONE_CHOICE' is not a known IANA timezone — keeping $current"
TIMEZONE_CHOICE=""
fi
return 0
fi
if ! ui_confirm "Set the server timezone? (current: $current)" no; then
return 0
fi
if ! command -v timedatectl >/dev/null 2>&1; then
ui_input TIMEZONE_CHOICE "IANA timezone" "Europe/Berlin"
else
if ! list_file="$(mktemp 2>/dev/null)"; then
ui_input TIMEZONE_CHOICE "IANA timezone" "Europe/Berlin"
else
timedatectl list-timezones >"$list_file" 2>/dev/null || true
ui_filter TIMEZONE_CHOICE "Europe/Berlin" <"$list_file"
rm -f "$list_file"
fi
fi
TIMEZONE_CHOICE="$(printf '%s' "$TIMEZONE_CHOICE" | tr -d '[:space:]')"
if [ -n "$TIMEZONE_CHOICE" ] && ! valid_timezone "$TIMEZONE_CHOICE"; then
warn "'$TIMEZONE_CHOICE' is not a known IANA timezone — keeping $current"
TIMEZONE_CHOICE=""
fi
}
# ─────────────────────────────────────────────────────────────────────────────
# 5. Timezone
# ─────────────────────────────────────────────────────────────────────────────
set_timezone() {
section "Time zone"
local current
current="$(current_timezone)"
if [ -z "$TIMEZONE_CHOICE" ]; then
ok "Left unchanged ($current)"
return 0
fi
if [ "$current" = "$TIMEZONE_CHOICE" ]; then
ok "Already $TIMEZONE_CHOICE"
return 0
fi
if have_systemd && command -v timedatectl >/dev/null 2>&1; then
if timedatectl set-timezone "$TIMEZONE_CHOICE" >>"$LOG_FILE" 2>&1; then
ok "Timezone set to $TIMEZONE_CHOICE"
return 0
fi
warn "timedatectl failed — falling back to /etc/localtime"
fi
if ln -sf "/usr/share/zoneinfo/$TIMEZONE_CHOICE" /etc/localtime 2>>"$LOG_FILE"; then
printf '%s\n' "$TIMEZONE_CHOICE" >/etc/timezone 2>>"$LOG_FILE" || true
ok "Timezone set to $TIMEZONE_CHOICE"
else
warn "couldn't set the timezone — keeping $current"
fi
}
# ─────────────────────────────────────────────────────────────────────────────
# 6. System update. Lock timeout + confdef/confold so a held dpkg lock or a
# changed config file can never turn this into an interactive prompt.
# ─────────────────────────────────────────────────────────────────────────────
apt_get() {
apt-get -y -qq \
-o DPkg::Lock::Timeout=300 \
-o Dpkg::Options::=--force-confdef \
-o Dpkg::Options::=--force-confold \
"$@"
}
apt_upgrade() {
section "System update"
export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
export -f apt_get
run_sh "Refreshing the package index" "Package index refreshed" 'apt_get update' \
|| warn "apt-get update reported problems — continuing anyway"
run_sh "Upgrading installed packages (the slow one)" "System up to date" 'apt_get full-upgrade' \
|| warn "some packages did not upgrade — see $LOG_FILE"
}
# ─────────────────────────────────────────────────────────────────────────────
# 7. Packages Iva needs, plus gh from its official apt repository.
# ─────────────────────────────────────────────────────────────────────────────
package_installed() {
local status
status="$(dpkg-query -W -f='${Status}' "$1" 2>/dev/null || true)"
case "$status" in
*"install ok installed"*) return 0 ;;
esac
return 1
}
install_packages() {
section "Packages"
export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
export -f apt_get
local missing=() pkg
for pkg in $PACKAGES; do
if ! package_installed "$pkg"; then
missing+=("$pkg")
fi
done
if [ "${#missing[@]}" -eq 0 ]; then
ok "All system packages already present"
else
export IVA_APT_PKGS="${missing[*]}"
# shellcheck disable=SC2016 # $IVA_APT_PKGS must expand in the child, not here
if run_sh "Installing: ${missing[*]}" "System packages installed" \
'apt_get install $IVA_APT_PKGS'; then
:
else
warn "some packages did not install — install.sh will report what is still missing"
fi
unset IVA_APT_PKGS
fi
install_gh
}
install_gh() {
if command -v gh >/dev/null 2>&1; then
ok "GitHub CLI already installed"
return 0
fi
CURRENT_STEP="installing the GitHub CLI"
local keyring="/etc/apt/keyrings/githubcli-archive-keyring.gpg"
# gh is not in the base Debian/Ubuntu repositories — add the official source.
# shellcheck disable=SC2174 # /etc/apt exists already; only keyrings is created here
if ! {
mkdir -p -m 755 /etc/apt/keyrings &&
curl -fsSL --connect-timeout 10 --retry 2 \
https://cli.github.com/packages/githubcli-archive-keyring.gpg -o "$keyring" &&
chmod go+r "$keyring"
} >>"$LOG_FILE" 2>&1; then
warn "couldn't add the GitHub CLI repository — install.sh sets gh up later"
return 0
fi
printf 'deb [arch=%s signed-by=%s] https://cli.github.com/packages stable main\n' \
"$(dpkg --print-architecture)" "$keyring" >/etc/apt/sources.list.d/github-cli.list