forked from Dicklesworthstone/agentic_coding_flywheel_setup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·4346 lines (3806 loc) · 175 KB
/
install.sh
File metadata and controls
executable file
·4346 lines (3806 loc) · 175 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
# shellcheck disable=SC1090,SC1091
# ============================================================
# ACFS - Agentic Coding Flywheel Setup
# Main installer script
#
# Usage:
# curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/agentic_coding_flywheel_setup/main/install.sh?$(date +%s)" | bash -s -- --yes --mode vibe
#
# Options:
# --yes Skip all prompts, use defaults
# --mode vibe Enable passwordless sudo, full agent permissions
# --dry-run Print what would be done without changing system
# --print Print upstream scripts/versions that will be run
# --skip-postgres Skip PostgreSQL 18 installation
# --skip-vault Skip HashiCorp Vault installation
# --skip-cloud Skip cloud CLIs (wrangler, supabase, vercel)
# --resume Resume from checkpoint (default when state exists)
# --force-reinstall Start fresh, ignore existing state
# --reset-state Move state file aside and exit (for debugging)
# --interactive Enable interactive prompts for resume decisions
# --skip-preflight Skip pre-flight system validation
# --skip-ubuntu-upgrade Skip automatic Ubuntu version upgrade
# --target-ubuntu=VER Set target Ubuntu version (default: 25.10)
# --strict Treat ALL tools as critical (any checksum mismatch aborts)
# --list-modules List available modules and exit
# --print-plan Print execution plan and exit (no installs)
# --only <module> Only run a specific module (repeatable)
# --only-phase <phase> Only run modules in a specific phase (repeatable)
# --skip <module> Skip a specific module (repeatable)
# --no-deps Disable automatic dependency closure (expert/debug)
# ============================================================
set -euo pipefail
# Prevent apt/dpkg from displaying interactive dialogs (kernel upgrade prompts,
# debconf questions, etc.) that corrupt the terminal with ncurses escape sequences
export DEBIAN_FRONTEND=noninteractive
export NEEDRESTART_MODE=a # Automatically restart services without asking
export NEEDRESTART_SUSPEND=1 # Suppress needrestart prompts during installation
export DEBCONF_NONINTERACTIVE_SEEN=true
# ============================================================
# Configuration
# ============================================================
ACFS_VERSION="0.3.0"
# Allow fork installations by overriding these via environment variables
ACFS_REPO_OWNER="${ACFS_REPO_OWNER:-Dicklesworthstone}"
ACFS_REPO_NAME="${ACFS_REPO_NAME:-agentic_coding_flywheel_setup}"
ACFS_REF="${ACFS_REF:-main}"
ACFS_RAW="https://raw.githubusercontent.com/${ACFS_REPO_OWNER}/${ACFS_REPO_NAME}/${ACFS_REF}"
export ACFS_RAW ACFS_VERSION
ACFS_COMMIT_SHA="" # Short SHA for display (12 chars)
ACFS_COMMIT_SHA_FULL="" # Full SHA for pinning resume scripts (40 chars)
# Early curl defaults: enforce HTTPS (including redirects) when supported.
# This is used before security.sh is available (bootstrap / early library sourcing).
ACFS_EARLY_CURL_ARGS=(-fsSL)
if command -v curl &>/dev/null && curl --help all 2>/dev/null | grep -q -- '--proto'; then
ACFS_EARLY_CURL_ARGS=(--proto '=https' --proto-redir '=https' -fsSL)
fi
# Note: ACFS_HOME is set after TARGET_HOME is determined
ACFS_LOG_DIR="/var/log/acfs"
# SCRIPT_DIR is empty when running via curl|bash (stdin; no file on disk)
SCRIPT_DIR=""
if [[ -n "${BASH_SOURCE[0]:-}" && -f "${BASH_SOURCE[0]}" ]]; then
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
fi
# Early PATH setup: ensure ~/.local/bin is available for native installers (e.g., Claude Code)
# This is critical because the Claude native installer puts the binary at ~/.local/bin/claude
export PATH="$HOME/.local/bin:$PATH"
# Default options
YES_MODE=false
DRY_RUN=false
PRINT_MODE=false
MODE="vibe"
SKIP_POSTGRES=false
SKIP_VAULT=false
SKIP_CLOUD=false
# Manifest-driven selection options (mjt.5.3)
LIST_MODULES=false
PRINT_PLAN_MODE=false
ONLY_MODULES=()
ONLY_PHASES=()
SKIP_MODULES=()
NO_DEPS=false
# Resume/reinstall options (used by state.sh confirm_resume)
export ACFS_FORCE_RESUME=false
export ACFS_FORCE_REINSTALL=false
# NOTE: When unset/empty, downstream libs default to interactive behavior when a TTY is available.
# install.sh forces non-interactive behavior in --yes mode.
export ACFS_INTERACTIVE="${ACFS_INTERACTIVE:-}"
RESET_STATE_ONLY=false
# Preflight options
SKIP_PREFLIGHT=false
# Ubuntu upgrade options (nb4: integrate upgrade phase)
SKIP_UBUNTU_UPGRADE=false
TARGET_UBUNTU_VERSION="25.10"
# Target user configuration
# Default: install for the "ubuntu" user (typical VPS images).
# Advanced: override with env vars (see README):
# TARGET_USER=myuser TARGET_HOME=/home/myuser ...
TARGET_USER="${TARGET_USER:-ubuntu}"
# Leave TARGET_HOME unset by default; init_target_paths will derive it from:
# - $HOME when running as TARGET_USER
# - /home/$TARGET_USER otherwise
TARGET_HOME="${TARGET_HOME:-}"
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
GRAY='\033[0;90m'
NC='\033[0m' # No Color
# Check if gum is available for enhanced UI
HAS_GUM=false
if command -v gum &>/dev/null; then
HAS_GUM=true
fi
# ============================================================
# Prevent logging.sh from overwriting our inline gum-enhanced functions
# ============================================================
export _ACFS_LOGGING_SH_LOADED=1
# ============================================================
# Minimal error-tracking fallbacks
# These are replaced once scripts/lib/error_tracking.sh is sourced (detect_environment()).
# ============================================================
type -t set_phase &>/dev/null || set_phase() { :; }
type -t try_step &>/dev/null || try_step() { shift; "$@"; }
type -t try_step_eval &>/dev/null || try_step_eval() { shift; bash -e -o pipefail -c "$1"; }
# ============================================================
# Installer libraries are sourced later in main() via detect_environment(), after
# bootstrapping the repo archive for curl|bash runs (prevents mixed refs).
# ============================================================
# ============================================================
# Source Ubuntu upgrade library for auto-upgrade functionality (nb4)
# ============================================================
_source_ubuntu_upgrade_lib() {
# Already loaded?
if [[ -n "${ACFS_UBUNTU_UPGRADE_LOADED:-}" ]]; then
return 0
fi
# Prefer bootstrapped libs when available (curl|bash mode), to avoid mixed refs.
if [[ -n "${ACFS_LIB_DIR:-}" ]] && [[ -f "$ACFS_LIB_DIR/ubuntu_upgrade.sh" ]]; then
# shellcheck source=scripts/lib/ubuntu_upgrade.sh
source "$ACFS_LIB_DIR/ubuntu_upgrade.sh"
export ACFS_UBUNTU_UPGRADE_LOADED=1
return 0
fi
# Try local file first (when running from repo)
if [[ -n "${SCRIPT_DIR:-}" ]] && [[ -f "$SCRIPT_DIR/scripts/lib/ubuntu_upgrade.sh" ]]; then
# shellcheck source=scripts/lib/ubuntu_upgrade.sh
source "$SCRIPT_DIR/scripts/lib/ubuntu_upgrade.sh"
export ACFS_UBUNTU_UPGRADE_LOADED=1
return 0
fi
# Try relative path (when running from repo root)
if [[ -f "./scripts/lib/ubuntu_upgrade.sh" ]]; then
source "./scripts/lib/ubuntu_upgrade.sh"
export ACFS_UBUNTU_UPGRADE_LOADED=1
return 0
fi
# Download for curl|bash scenario
if command -v curl &>/dev/null; then
local tmp_upgrade=""
if command -v mktemp &>/dev/null; then
tmp_upgrade="$(mktemp "${TMPDIR:-/tmp}/acfs-ubuntu-upgrade.XXXXXX" 2>/dev/null)" || tmp_upgrade=""
fi
if [[ -n "$tmp_upgrade" ]] && curl "${ACFS_EARLY_CURL_ARGS[@]}" "$ACFS_RAW/scripts/lib/ubuntu_upgrade.sh" -o "$tmp_upgrade" 2>/dev/null; then
source "$tmp_upgrade"
rm -f "$tmp_upgrade"
export ACFS_UBUNTU_UPGRADE_LOADED=1
return 0
fi
fi
# If we can't load it, return failure (caller should handle)
return 1
}
# ACFS Color scheme (Catppuccin Mocha inspired)
ACFS_PRIMARY="#89b4fa"
ACFS_SUCCESS="#a6e3a1"
ACFS_WARNING="#f9e2af"
ACFS_ERROR="#f38ba8"
ACFS_MUTED="#6c7086"
# ============================================================
# Fetch commit SHA and date from GitHub API
# This ensures we always know exactly which version is running
# ============================================================
export ACFS_COMMIT_DATE="" # exported for child processes/debugging
ACFS_COMMIT_AGE=""
fetch_commit_sha() {
# Already have it? Skip
if [[ -n "$ACFS_COMMIT_SHA" && "$ACFS_COMMIT_SHA" != "(unknown)" ]]; then
return 0
fi
# Need curl
if ! command -v curl &>/dev/null; then
ACFS_COMMIT_SHA="(curl not available)"
return 0
fi
# Fetch from GitHub API - get the commit SHA for the ref
local api_url="https://api.github.com/repos/${ACFS_REPO_OWNER}/${ACFS_REPO_NAME}/commits/${ACFS_REF}"
local response
if response=$(curl -sf --max-time 5 "$api_url" 2>/dev/null); then
# Try to use python3 for robust JSON parsing if available
local sha=""
local commit_date=""
if command -v python3 &>/dev/null; then
# Python parsing - robust against JSON formatting changes
sha=$(echo "$response" | python3 -c "import sys, json; print(json.load(sys.stdin).get('sha', ''))" 2>/dev/null)
commit_date=$(echo "$response" | python3 -c "import sys, json; print(json.load(sys.stdin).get('commit', {}).get('author', {}).get('date', ''))" 2>/dev/null)
else
# Fallback: Extract SHA from JSON using grep/sed (works without jq/python)
# Use grep -o to handle minified JSON (puts matches on new lines)
sha=$(echo "$response" | grep -o '"sha":[[:space:]]*"[^"]*"' | head -n 1 | sed 's/.*"\([a-f0-9]*\)".*/\1/')
# Extract commit date (format: "2025-12-21T10:30:00Z")
commit_date=$(echo "$response" | grep -o '"date":[[:space:]]*"[^"]*"' | head -n 1 | sed 's/.*"\([^"]*\)".*/\1/')
fi
if [[ -n "$sha" && ${#sha} -ge 7 ]]; then
ACFS_COMMIT_SHA="${sha:0:12}"
# shellcheck disable=SC2034 # Used by scripts/lib/ubuntu_upgrade.sh to pin resume scripts to a specific commit.
[[ ${#sha} -ge 40 ]] && ACFS_COMMIT_SHA_FULL="$sha"
fi
if [[ -n "$commit_date" ]]; then
ACFS_COMMIT_DATE="$commit_date"
# Calculate age
local now commit_ts age_seconds
now=$(date +%s 2>/dev/null || echo 0)
# Parse ISO 8601 date - handle both GNU and BSD date
if date -d "$commit_date" +%s &>/dev/null; then
# GNU date
commit_ts=$(date -d "$commit_date" +%s 2>/dev/null || echo 0)
else
# BSD date - try simpler parsing
commit_ts=$(date -j -f "%Y-%m-%dT%H:%M:%SZ" "$commit_date" +%s 2>/dev/null || echo 0)
fi
if [[ "$now" -gt 0 && "$commit_ts" -gt 0 ]]; then
age_seconds=$((now - commit_ts))
# Handle negative age (clock skew / future commit)
if [[ $age_seconds -lt 0 ]]; then
ACFS_COMMIT_AGE="just now"
elif [[ $age_seconds -lt 60 ]]; then
ACFS_COMMIT_AGE="${age_seconds}s ago"
elif [[ $age_seconds -lt 3600 ]]; then
ACFS_COMMIT_AGE="$((age_seconds / 60))m ago"
elif [[ $age_seconds -lt 86400 ]]; then
ACFS_COMMIT_AGE="$((age_seconds / 3600))h ago"
else
ACFS_COMMIT_AGE="$((age_seconds / 86400))d ago"
fi
fi
fi
if [[ -n "$ACFS_COMMIT_SHA" ]]; then
return 0
fi
fi
# Fallback
ACFS_COMMIT_SHA="(unknown)"
}
# ============================================================
# Install gum FIRST for beautiful UI from the start
# ============================================================
install_gum_early() {
# Already have gum? Great!
if command -v gum &>/dev/null; then
HAS_GUM=true
return 0
fi
# Respect dry-run / print-only modes: do not modify the system just to
# improve UI.
if [[ "${DRY_RUN:-false}" == "true" ]] || [[ "${PRINT_MODE:-false}" == "true" ]]; then
return 0
fi
# Only attempt early gum install on supported Ubuntu systems.
# Preflight/ensure_ubuntu will stop execution later, but this prevents
# partial modifications (apt repo/key) on unsupported OS versions.
if [[ -f /etc/os-release ]]; then
# shellcheck disable=SC1091
source /etc/os-release
local version_id="${VERSION_ID:-}"
local version_major="${version_id%%.*}"
if [[ "${ID:-}" != "ubuntu" ]] || [[ -z "$version_id" ]] || [[ "$version_major" -lt 22 ]]; then
return 0
fi
else
return 0
fi
# Need curl to fetch gum - if curl isn't installed yet, skip early install
# (gum will be installed later in install_cli_tools after ensure_base_deps)
if ! command -v curl &>/dev/null; then
return 0
fi
# Need gpg for apt key handling
if ! command -v gpg &>/dev/null; then
return 0
fi
# Need apt-get for installation
if ! command -v apt-get &>/dev/null; then
return 0
fi
# Need root/sudo for apt operations
local sudo_cmd=""
if [[ $EUID -ne 0 ]]; then
if command -v sudo &>/dev/null; then
sudo_cmd="sudo"
else
# Can't install gum without sudo, fall back to plain output
return 0
fi
fi
echo -e "\033[0;90m → Installing gum for enhanced UI...\033[0m" >&2
# Step 1: Fetch Charm GPG key (with timeout)
echo -e "\033[0;90m ↳ Fetching Charm repository key...\033[0m" >&2
$sudo_cmd mkdir -p /etc/apt/keyrings 2>/dev/null || true
if ! curl --connect-timeout 10 --max-time 30 -fsSL https://repo.charm.sh/apt/gpg.key 2>/dev/null | \
$sudo_cmd gpg --batch --yes --dearmor -o /etc/apt/keyrings/charm.gpg 2>/dev/null; then
echo -e "\033[0;33m ⚠ Could not fetch Charm key (skipping gum, will retry later)\033[0m" >&2
return 0
fi
# Step 2: Add apt repository (using DEB822 format to avoid .migrate warnings on upgrade)
$sudo_cmd tee /etc/apt/sources.list.d/charm.sources > /dev/null 2>&1 << 'EOF'
Types: deb
URIs: https://repo.charm.sh/apt/
Suites: *
Components: *
Signed-By: /etc/apt/keyrings/charm.gpg
EOF
# Step 3: Update apt (this can be slow on fresh systems)
# Disable fancy progress to prevent terminal cursor issues
echo -e "\033[0;90m ↳ Updating package lists (may take 30-60s on fresh systems)...\033[0m" >&2
if ! DEBIAN_FRONTEND=noninteractive timeout 120 $sudo_cmd apt-get update -y \
-o Dpkg::Progress-Fancy="0" -o APT::Color="0" >/dev/null 2>&1; then
# Reset terminal line position in case apt left cursor in bad state
echo -e "\r\033[K\033[0;33m ⚠ apt-get update slow/failed (skipping gum, will retry later)\033[0m" >&2
return 0
fi
# Step 4: Install gum
# Use DEBIAN_FRONTEND=noninteractive and disable fancy progress to prevent
# terminal cursor position issues when apt-get fails or times out
echo -e "\033[0;90m ↳ Installing gum package...\033[0m" >&2
local apt_output
if apt_output=$(DEBIAN_FRONTEND=noninteractive timeout 60 $sudo_cmd apt-get install -y \
-o Dpkg::Progress-Fancy="0" -o APT::Color="0" gum 2>&1); then
HAS_GUM=true
# Reset terminal line position and show success
echo -e "\r\033[K\033[0;32m ✓ gum installed - enhanced UI enabled!\033[0m" >&2
else
# Reset terminal line position in case apt left cursor in bad state
echo -e "\r\033[K\033[0;33m ⚠ gum install failed (continuing without enhanced UI)\033[0m" >&2
# Show brief reason if available (e.g., "Unable to locate package", timeout, etc.)
if echo "$apt_output" | grep -qi "unable to locate\|not found\|timeout"; then
echo -e "\033[0;90m (Charm repository may be unavailable or package not found)\033[0m" >&2
fi
fi
}
# ============================================================
# ASCII Art Banner
# ============================================================
print_banner() {
# Ensure terminal is in a clean state before printing banner
# (previous apt/dpkg operations may have left cursor in bad position)
echo -e "\r\033[K" >&2
# Build version line with proper padding (63 chars inner width)
local version_text="Agentic Coding Flywheel Setup v${ACFS_VERSION}"
local padding=$(( (63 - ${#version_text}) / 2 ))
local version_line
version_line=$(printf "║%*s%s%*s║" "$padding" "" "$version_text" "$((63 - padding - ${#version_text}))" "")
# Build commit info line
local commit_text=""
if [[ -n "$ACFS_COMMIT_SHA" && "$ACFS_COMMIT_SHA" != "(unknown)" ]]; then
commit_text="Commit: ${ACFS_COMMIT_SHA}"
if [[ -n "$ACFS_COMMIT_AGE" ]]; then
commit_text="${commit_text} (${ACFS_COMMIT_AGE})"
fi
fi
local commit_padding=$(( (63 - ${#commit_text}) / 2 ))
local commit_line
if [[ -n "$commit_text" ]]; then
commit_line=$(printf "║%*s%s%*s║" "$commit_padding" "" "$commit_text" "$((63 - commit_padding - ${#commit_text}))" "")
else
commit_line="║ ║"
fi
local banner="
╔═══════════════════════════════════════════════════════════════╗
║ ║
║ █████╗ ██████╗███████╗███████╗ ║
║ ██╔══██╗██╔════╝██╔════╝██╔════╝ ║
║ ███████║██║ █████╗ ███████╗ ║
║ ██╔══██║██║ ██╔══╝ ╚════██║ ║
║ ██║ ██║╚██████╗██║ ███████║ ║
║ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚══════╝ ║
║ ║
${version_line}
${commit_line}
║ ║
╚═══════════════════════════════════════════════════════════════╝
"
if [[ "$HAS_GUM" == "true" ]]; then
echo "$banner" | gum style --foreground "$ACFS_PRIMARY" --bold >&2
else
echo -e "${BLUE}$banner${NC}" >&2
fi
}
# ============================================================
# Logging functions (with gum enhancement)
# ============================================================
log_step() {
local step="${1:-}"
local message="${2:-}"
# Allow single-arg usage: treat the arg as the message
if [[ -z "$message" ]]; then
message="$step"
step="*"
fi
if [[ "$HAS_GUM" == "true" ]]; then
gum style --foreground "$ACFS_PRIMARY" --bold "[$step]" | tr -d '\n' >&2
echo -n " " >&2
gum style "$message" >&2
else
echo -e "${BLUE}[$step]${NC} $message" >&2
fi
}
log_detail() {
if [[ "$HAS_GUM" == "true" ]]; then
gum style --foreground "$ACFS_MUTED" --margin "0 0 0 4" "→ $1" >&2
else
echo -e "${GRAY} → $1${NC}" >&2
fi
}
log_info() {
log_detail "$1"
}
log_success() {
if [[ "$HAS_GUM" == "true" ]]; then
gum style --foreground "$ACFS_SUCCESS" --bold "✓ $1" >&2
else
echo -e "${GREEN}✓ $1${NC}" >&2
fi
}
log_warn() {
if [[ "$HAS_GUM" == "true" ]]; then
gum style --foreground "$ACFS_WARNING" "⚠ $1" >&2
else
echo -e "${YELLOW}⚠ $1${NC}" >&2
fi
}
log_error() {
if [[ "$HAS_GUM" == "true" ]]; then
gum style --foreground "$ACFS_ERROR" --bold "✖ $1" >&2
else
echo -e "${RED}✖ $1${NC}" >&2
fi
}
log_fatal() {
log_error "$1"
exit 1
}
log_section() {
if [[ "$HAS_GUM" == "true" ]]; then
echo "" >&2
gum style --foreground "$ACFS_PRIMARY" --bold "═══ $1 ═══" >&2
else
echo "" >&2
echo -e "${BLUE}═══ $1 ═══${NC}" >&2
fi
}
# ============================================================
# Error handling
# ============================================================
cleanup() {
local exit_code=$?
if [[ $exit_code -ne 0 ]]; then
log_error ""
if [[ "${SMOKE_TEST_FAILED:-false}" == "true" ]]; then
log_error "ACFS installation completed, but the post-install smoke test failed."
else
log_error "ACFS installation failed!"
fi
log_error ""
log_error "To debug:"
log_error " 1. Check the log: cat $ACFS_LOG_DIR/install.log"
log_error " 2. If installed, run: acfs doctor (try as $TARGET_USER)"
log_error " (If you ran the installer as root: sudo -u $TARGET_USER -i bash -lc 'acfs doctor')"
log_error " 3. Re-run this installer (it's safe to run multiple times)"
log_error ""
fi
}
trap cleanup EXIT
# ============================================================
# Parse arguments
# ============================================================
parse_args() {
while [[ $# -gt 0 ]]; do
case $1 in
--yes|-y)
YES_MODE=true
shift
;;
--dry-run)
DRY_RUN=true
shift
;;
--print)
PRINT_MODE=true
shift
;;
--mode)
if [[ -z "${2:-}" ]]; then
log_fatal "--mode requires a value (e.g., --mode vibe)"
fi
MODE="$2"
case "$MODE" in
vibe|safe) ;;
*)
log_fatal "Invalid --mode '$MODE' (expected: vibe or safe)"
;;
esac
shift 2
;;
--skip-postgres)
SKIP_POSTGRES=true
shift
;;
--skip-vault)
SKIP_VAULT=true
shift
;;
--skip-cloud)
SKIP_CLOUD=true
shift
;;
--resume)
export ACFS_FORCE_RESUME=true
shift
;;
--force-reinstall)
export ACFS_FORCE_REINSTALL=true
shift
;;
--reset-state)
RESET_STATE_ONLY=true
shift
;;
--interactive)
export ACFS_INTERACTIVE=true
shift
;;
--strict)
# Treat all tools as critical - any checksum mismatch aborts
# Related: bead 8mv, tools.sh ACFS_STRICT_MODE handling
export ACFS_STRICT_MODE=true
shift
;;
--skip-preflight)
SKIP_PREFLIGHT=true
shift
;;
--skip-ubuntu-upgrade)
# Skip automatic Ubuntu version upgrade (nb4)
# shellcheck disable=SC2034 # used by run_ubuntu_upgrade_phase
SKIP_UBUNTU_UPGRADE=true
shift
;;
--target-ubuntu|--target-ubuntu=*)
# Set target Ubuntu version for auto-upgrade (nb4)
if [[ "$1" == "--target-ubuntu" ]]; then
if [[ -z "${2:-}" ]]; then
log_fatal "--target-ubuntu requires a version (e.g., --target-ubuntu 25.10)"
fi
# shellcheck disable=SC2034 # used by run_ubuntu_upgrade_phase
TARGET_UBUNTU_VERSION="$2"
shift 2
else
# Handle --target-ubuntu=25.10 format
# shellcheck disable=SC2034 # used by run_ubuntu_upgrade_phase
TARGET_UBUNTU_VERSION="${1#*=}"
shift
fi
;;
--list-modules)
LIST_MODULES=true
shift
;;
--print-plan)
PRINT_PLAN_MODE=true
shift
;;
--only)
# Add module to ONLY_MODULES list (for manifest-driven selection)
if [[ -z "${2:-}" ]]; then
log_fatal "--only requires a module ID"
fi
ONLY_MODULES+=("$2")
shift 2
;;
--only-phase)
# Add phase to ONLY_PHASES list
if [[ -z "${2:-}" ]]; then
log_fatal "--only-phase requires a phase number"
fi
ONLY_PHASES+=("$2")
shift 2
;;
--skip)
# Add module to SKIP_MODULES list
if [[ -z "${2:-}" ]]; then
log_fatal "--skip requires a module ID"
fi
SKIP_MODULES+=("$2")
shift 2
;;
--no-deps)
# Disable automatic dependency resolution
NO_DEPS=true
shift
;;
*)
log_warn "Unknown option: $1"
shift
;;
esac
done
}
# ============================================================
# Utility functions
# ============================================================
command_exists() {
command -v "$1" &>/dev/null
}
# ============================================================
# Environment Detection (mjt.5.3)
# Sets up paths for libs and generated scripts BEFORE sourcing them.
# ============================================================
detect_environment() {
# Set lib and generated script directories based on context
if [[ -n "${ACFS_BOOTSTRAP_DIR:-}" ]]; then
# curl|bash mode: use bootstrap archive
ACFS_LIB_DIR="$ACFS_BOOTSTRAP_DIR/scripts/lib"
ACFS_GENERATED_DIR="$ACFS_BOOTSTRAP_DIR/scripts/generated"
ACFS_ASSETS_DIR="${ACFS_ASSETS_DIR:-$ACFS_BOOTSTRAP_DIR/acfs}"
ACFS_CHECKSUMS_YAML="${ACFS_CHECKSUMS_YAML:-$ACFS_BOOTSTRAP_DIR/checksums.yaml}"
ACFS_MANIFEST_YAML="${ACFS_MANIFEST_YAML:-$ACFS_BOOTSTRAP_DIR/acfs.manifest.yaml}"
elif [[ -n "${SCRIPT_DIR:-}" ]]; then
# Local checkout mode
ACFS_LIB_DIR="$SCRIPT_DIR/scripts/lib"
ACFS_GENERATED_DIR="$SCRIPT_DIR/scripts/generated"
ACFS_ASSETS_DIR="$SCRIPT_DIR/acfs"
ACFS_CHECKSUMS_YAML="$SCRIPT_DIR/checksums.yaml"
ACFS_MANIFEST_YAML="$SCRIPT_DIR/acfs.manifest.yaml"
else
# Fallback: current directory
ACFS_LIB_DIR="./scripts/lib"
ACFS_GENERATED_DIR="./scripts/generated"
ACFS_ASSETS_DIR="./acfs"
ACFS_CHECKSUMS_YAML="./checksums.yaml"
ACFS_MANIFEST_YAML="./acfs.manifest.yaml"
fi
export ACFS_LIB_DIR ACFS_GENERATED_DIR ACFS_ASSETS_DIR ACFS_CHECKSUMS_YAML ACFS_MANIFEST_YAML
# Source minimal libs in correct order (logging, then helpers)
if [[ -f "$ACFS_LIB_DIR/logging.sh" ]]; then
# shellcheck source=scripts/lib/logging.sh
source "$ACFS_LIB_DIR/logging.sh"
fi
if [[ -f "$ACFS_LIB_DIR/security.sh" ]]; then
# shellcheck source=scripts/lib/security.sh
source "$ACFS_LIB_DIR/security.sh"
fi
if [[ -f "$ACFS_LIB_DIR/contract.sh" ]]; then
# shellcheck source=scripts/lib/contract.sh
source "$ACFS_LIB_DIR/contract.sh"
fi
if [[ -f "$ACFS_LIB_DIR/install_helpers.sh" ]]; then
# shellcheck source=scripts/lib/install_helpers.sh
source "$ACFS_LIB_DIR/install_helpers.sh"
fi
if [[ -f "$ACFS_LIB_DIR/user.sh" ]]; then
# shellcheck source=scripts/lib/user.sh
source "$ACFS_LIB_DIR/user.sh"
fi
# Source state management for resume/progress tracking (mjt.5.8)
if [[ -f "$ACFS_LIB_DIR/state.sh" ]]; then
# shellcheck source=scripts/lib/state.sh
source "$ACFS_LIB_DIR/state.sh"
fi
# Source error pattern matcher (report.sh uses get_suggested_fix when available).
if [[ -f "$ACFS_LIB_DIR/errors.sh" ]]; then
# shellcheck source=scripts/lib/errors.sh
source "$ACFS_LIB_DIR/errors.sh"
fi
# Source structured failure/success reporting (mjt.5.8).
if [[ -f "$ACFS_LIB_DIR/report.sh" ]]; then
# shellcheck source=scripts/lib/report.sh
source "$ACFS_LIB_DIR/report.sh"
fi
# Source error tracking for try_step wrappers (mjt.5.8)
if [[ -f "$ACFS_LIB_DIR/error_tracking.sh" ]]; then
# shellcheck source=scripts/lib/error_tracking.sh
source "$ACFS_LIB_DIR/error_tracking.sh"
fi
# Source Ubuntu upgrade library from the same lib dir when available (nb4).
if [[ -f "$ACFS_LIB_DIR/ubuntu_upgrade.sh" ]]; then
# shellcheck source=scripts/lib/ubuntu_upgrade.sh
source "$ACFS_LIB_DIR/ubuntu_upgrade.sh"
export ACFS_UBUNTU_UPGRADE_LOADED=1
fi
# Source tailscale installer (bt5)
if [[ -f "$ACFS_LIB_DIR/tailscale.sh" ]]; then
# shellcheck source=scripts/lib/tailscale.sh
source "$ACFS_LIB_DIR/tailscale.sh"
fi
# Source manifest index (data-only, safe to source)
if [[ -f "$ACFS_GENERATED_DIR/manifest_index.sh" ]]; then
# shellcheck source=scripts/generated/manifest_index.sh
source "$ACFS_GENERATED_DIR/manifest_index.sh"
ACFS_MANIFEST_INDEX_LOADED=true
else
ACFS_MANIFEST_INDEX_LOADED=false
fi
export ACFS_MANIFEST_INDEX_LOADED
}
# ============================================================
# Source Generated Installers (mjt.5.6)
# Loads generated category scripts for module functions.
# ============================================================
source_generated_installers() {
if [[ "${ACFS_GENERATED_SOURCED:-false}" == "true" ]]; then
return 0
fi
if [[ -z "${ACFS_GENERATED_DIR:-}" ]]; then
log_warn "ACFS_GENERATED_DIR not set; cannot source generated installers"
return 0
fi
if [[ ! -d "$ACFS_GENERATED_DIR" ]]; then
log_warn "Generated installers directory not found: $ACFS_GENERATED_DIR"
return 0
fi
local script=""
local scripts=(
"install_users.sh"
"install_base.sh"
"install_filesystem.sh"
"install_shell.sh"
"install_cli.sh"
"install_network.sh"
"install_lang.sh"
"install_tools.sh"
"install_agents.sh"
"install_db.sh"
"install_cloud.sh"
"install_stack.sh"
"install_acfs.sh"
)
for script in "${scripts[@]}"; do
if [[ -f "$ACFS_GENERATED_DIR/$script" ]]; then
# shellcheck source=/dev/null
source "$ACFS_GENERATED_DIR/$script"
fi
done
ACFS_GENERATED_SOURCED=true
export ACFS_GENERATED_SOURCED
}
# ============================================================
# List Modules (mjt.5.3)
# Prints available modules from manifest_index.sh
# ============================================================
list_modules() {
if [[ "${ACFS_MANIFEST_INDEX_LOADED:-false}" != "true" ]]; then
echo "Error: Manifest index not loaded. Cannot list modules." >&2
return 1
fi
echo "Available ACFS Modules"
echo "======================"
echo ""
local current_phase=""
local module=""
local phase=""
local category=""
local deps=""
local enabled=""
local key=""
local enabled_marker=""
for module in "${ACFS_MODULES_IN_ORDER[@]}"; do
# Use key variable to prevent arithmetic evaluation with dots
key="$module"
phase="${ACFS_MODULE_PHASE[$key]:-?}"
category="${ACFS_MODULE_CATEGORY[$key]:-?}"
deps="${ACFS_MODULE_DEPS[$key]:-none}"
enabled="${ACFS_MODULE_DEFAULT[$key]:-1}"
if [[ "$phase" != "$current_phase" ]]; then
echo ""
echo "Phase $phase:"
current_phase="$phase"
fi
enabled_marker="+"
if [[ "$enabled" == "0" || "$enabled" == "false" ]]; then
enabled_marker="-"
fi
echo " [$enabled_marker] $module ($category)"
if [[ -n "$deps" ]] && [[ "$deps" != "none" ]]; then
echo " deps: $deps"
fi
done
echo ""
echo "Legend: [+] enabled by default, [-] optional"
echo "Total: ${#ACFS_MODULES_IN_ORDER[@]} modules"
}
# ============================================================
# Print Plan (mjt.5.3)
# Prints the effective execution plan without running installs.
# ============================================================
print_execution_plan() {
if [[ "${ACFS_MANIFEST_INDEX_LOADED:-false}" != "true" ]]; then
echo "Error: Manifest index not loaded. Cannot print plan." >&2
return 1
fi
echo "ACFS Installation Plan"
echo "======================"
echo ""
echo "Mode: $MODE"
echo "Selected modules: ${#ACFS_EFFECTIVE_PLAN[@]} of ${#ACFS_MODULES_IN_ORDER[@]} available"
echo ""
# Show selection settings if non-default
if [[ ${#ONLY_MODULES[@]} -gt 0 ]]; then
echo "Selection: --only ${ONLY_MODULES[*]}"
elif [[ ${#ONLY_PHASES[@]} -gt 0 ]]; then
echo "Selection: --only-phase ${ONLY_PHASES[*]}"
fi
if [[ ${#SKIP_MODULES[@]} -gt 0 ]]; then
echo "Skipped: --skip ${SKIP_MODULES[*]}"
fi
if [[ "${NO_DEPS:-false}" == "true" ]]; then
echo "⚠ --no-deps: dependencies NOT auto-installed"
fi
echo ""
echo "Execution order:"
echo ""
local idx=1
local module phase func key reason
for module in "${ACFS_EFFECTIVE_PLAN[@]}"; do
# Use key variable to prevent arithmetic evaluation with dots
key="$module"
phase="${ACFS_MODULE_PHASE[$key]:-?}"
func="${ACFS_MODULE_FUNC[$key]:-?}"
reason="${ACFS_PLAN_REASON[$key]:-}"
if [[ -n "$reason" ]]; then
printf " %2d. [Phase %s] %s -> %s() (%s)\n" "$idx" "$phase" "$module" "$func" "$reason"
else
printf " %2d. [Phase %s] %s -> %s()\n" "$idx" "$phase" "$module" "$func"
fi
((++idx)) # Use ++idx to avoid exit on zero under set -e
done
echo ""
echo "Legacy options (will be migrated to --skip):"
echo " --skip-postgres: $SKIP_POSTGRES"
echo " --skip-vault: $SKIP_VAULT"
echo " --skip-cloud: $SKIP_CLOUD"
echo ""
echo "This is a preview. Run without --print-plan to execute."
}
# ============================================================
# Pre-Flight Validation
# ============================================================
# Runs system validation checks before installation begins.
# Related beads: agentic_coding_flywheel_setup-545
run_preflight_checks() {
log_step "0/9" "Running pre-flight validation..."
local preflight_script=""
local preflight_tmp=""
# Try to find preflight script in different locations
if [[ -n "${ACFS_BOOTSTRAP_DIR:-}" ]] && [[ -f "$ACFS_BOOTSTRAP_DIR/scripts/preflight.sh" ]]; then
preflight_script="$ACFS_BOOTSTRAP_DIR/scripts/preflight.sh"
elif [[ -n "${SCRIPT_DIR:-}" ]] && [[ -f "$SCRIPT_DIR/scripts/preflight.sh" ]]; then
preflight_script="$SCRIPT_DIR/scripts/preflight.sh"
elif [[ -f "./scripts/preflight.sh" ]]; then
preflight_script="./scripts/preflight.sh"
else
# Download preflight script for curl | bash scenario (if curl available)
if command -v curl &>/dev/null; then
log_detail "Downloading preflight script..."
if command -v mktemp &>/dev/null; then
preflight_tmp="$(mktemp "${TMPDIR:-/tmp}/acfs-preflight.XXXXXX" 2>/dev/null)" || preflight_tmp=""
fi
if [[ -n "$preflight_tmp" ]] && acfs_curl -o "$preflight_tmp" "$ACFS_RAW/scripts/preflight.sh" 2>/dev/null; then
chmod +x "$preflight_tmp"
preflight_script="$preflight_tmp"
else
log_warn "Could not download preflight script - skipping checks"
return 0
fi
else
log_warn "curl not available - skipping preflight checks"
return 0
fi
fi
# Run preflight checks and capture exit code correctly
# (can't use "if ! cmd; then exit_code=$?" because $? would be 0 from the negation)
local exit_code=0
bash "$preflight_script" || exit_code=$?
if [[ $exit_code -ne 0 ]]; then
echo "" >&2