-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrun.bash
More file actions
executable file
·2691 lines (2467 loc) · 123 KB
/
Copy pathrun.bash
File metadata and controls
executable file
·2691 lines (2467 loc) · 123 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
## Setup
## !! BUMP THIS VERSION ON EVERY CHANGE TO THIS FILE — NO EXCEPTIONS !!
## !! If you forget, there is NO WAY to tell which version is running !!
RUN_BASH_VERSION="1.11.0" # Feature (Plan 00063) slice 2: headless PREFLIGHT — headless_preflight validates+resolves all RUN_BASH_* input up front (non-root check, NOPASSWD-sudo probe, required email/accounts, secret *_FILE resolution with V3.10 guardrails: file-precedence, both-set/unreadable/literal-on-cloud fail-fast, literal-elsewhere warn, unset literals before first child), set -u-safe secret-file EXIT trap. v1.9.1: defer the GitHub-empty ('none') path per round-3 decision — headless v1 requires a single GitHub account + token file (fail fast on 'none'); help + acceptance aligned. v1.9.2: require RUN_BASH_GITHUB_SSH_PASSPHRASE_FILE in v1 — the login SSH key stays passphrase-protected (D6), mirroring the interactive no-empty-passphrase rule, since headless loads it non-interactively via ssh-agent/SSH_ASKPASS (D5). v1.9.3: begin the EXECUTION slice — add hl_abort (BIG LOUD banner, exit 1) for headless execution failures, and a headless backstop at the top of every shared interactive prompt helper (confirm/promptForValue/promptChoice/promptSecretConfirmed/promptDefault/prompt_verified_vault_password/prompt_github_accounts_yaml) so a headless run that ever reaches a prompt fails LOUD instead of hanging (fail-fast rule 11). v1.9.4: GitHub/SSH execution mechanics — hl_ssh_agent_start (ssh-agent + transient 0700 SSH_ASKPASS reading a 0600 passphrase file, V3.13), hl_ssh_agent_stop (kill after last git op, V3.12), hl_cleanup EXIT trap (shred secret files + backstop agent kill, V3.11); headless branches for keygen (-P from resolved passphrase + agent load), hostname (RUN_BASH_HOSTNAME or leave default), gh token auth (gh auth login --with-token from stdin + git_protocol=ssh). All fail LOUD via hl_abort. v1.9.5: localhost.yml assembly — hl_write_localhost_yml (idempotent keep, else RUN_BASH_CONFIG_SOURCE pull from the private config repo, else FRESH from RUN_BASH_* identity + github_accounts), hl_pull_config_source (private-repo gate + LOUD 404), hl_reconcile_vault (D6: provided-or-fail, verify against encrypted values, NEVER auto-generate over !vault); headless branch for github_ssh_passphrase (reuse resolved passphrase, vault-encrypt). Interactive config/vault blocks wrapped under `if HEADLESS != true`. v1.10.0: FLIP the honest-stop — headless now flows through the FULL body (gh-account-setup gets RUN_BASH_HEADLESS + fails LOUD on any interactive gh web/scope-refresh; main playbook gets RUN_BASH_PROVISIONING_PROFILE passthrough + D7 loud-fatal on failure; optional playbooks via RUN_BASH_OPTIONAL_PLAYBOOKS; projects restore via RUN_BASH_RESTORE_PROJECTS; reboot via RUN_BASH_REBOOT). END-TO-END execution is HOST-verified on a real server (Phase 3) — in-container this is bash -n + shellcheck + preflight acceptance only. v1.11.0: Feature (Plan 00065 Phase 5) — RUN_BASH_OPTIONAL_PLAYBOOKS accepts the reserved keyword 'server-recommended', expanded from the tracked manifest playbooks/imports/optional/server-recommended.bundle into its listed plays before the existing per-token resolver runs; composes with explicit tokens and the resolved token list is de-duplicated (a play named twice — via the bundle plus an explicit token, or two explicit tokens — runs once); unknown-token and failed-play handling unchanged.
# ── Sourced-shell pollution guard (H4) ───────────────────────────────────────
# The documented install is `(source <(curl ... run.bash))` — sourced INSIDE a
# subshell (the parens). The parens are LOAD-BEARING: they contain set -e / IFS /
# trap / exit so they never leak into or kill the user's interactive shell.
#
# The whole executable body is wrapped in main() (see end of file) and only runs
# when main "$@" is called on the last line. main() runs everything in an explicit
# subshell ( ... ) of its own, so set -e / IFS / trap / exit are contained there
# regardless of how the file was loaded. That makes the bare-source case
# (`source <(curl ...)` without the documented parens) safe too: nothing escapes
# into the caller's interactive shell. The documented parenthesised path keeps
# working unchanged. set -e / IFS / pipefail are therefore set INSIDE main(), not
# at top level, so they never touch a sourcing shell.
## Colors and formatting (constants — safe at top level even if sourced)
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m' # No Color
## Unicode symbols
CHECK="✓"
CROSS="✗"
ARROW="➜"
INFO="ℹ"
WARN="⚠"
BUG="🐛"
# ── Headless / unattended helpers (Plan 00063) ───────────────────────────────
# Defined at TOP LEVEL (before main) so they are available in the early
# flags/preflight region, which runs before main()'s nested functions exist.
# They depend only on the colour/symbol constants above. Fail-fast rule 11:
# a headless run never hangs — a missing/unsafe input aborts with a specific,
# actionable message on stderr.
# headless_fail <what-is-wrong> <how-to-fix> — abort a headless run (exit 1).
# MUST be called directly (never inside $(...)) so exit ends the whole script.
headless_fail() {
echo -e "\n${RED}${BOLD}${CROSS} Headless run cannot proceed${NC}" >&2
echo -e "${RED} ${1}${NC}" >&2
echo -e "${YELLOW}${ARROW} ${2}${NC}" >&2
echo -e "${YELLOW}${ARROW} Full contract: ./run.bash --help-run-headless${NC}" >&2
exit 1
}
# hl_abort <step> <what-failed> [how-to-debug] — BIG LOUD, unmissable abort for a
# headless EXECUTION failure (after preflight, during actual provisioning). The
# whole point of headless is an unattended run the operator is NOT watching live, so
# any failure must SCREAM: a red banner naming the exact step, the concrete reason,
# and a debug pointer — then exit non-zero so the run never limps on or hangs.
# MUST be called directly (never inside $(...)) so exit ends the whole script.
hl_abort() {
local _step="$1" _what="$2" _debug="${3:-}"
{
echo -e "\n${RED}${BOLD}╔════════════════════════════════════════════════════════════════╗${NC}"
echo -e "${RED}${BOLD}║ HEADLESS PROVISIONING FAILED — run.bash v${RUN_BASH_VERSION}${NC}"
echo -e "${RED}${BOLD}╚════════════════════════════════════════════════════════════════╝${NC}"
echo -e "${RED}${BOLD} STEP :${NC} ${_step}"
echo -e "${RED}${BOLD} WHY :${NC} ${_what}"
if [[ -n "$_debug" ]]; then
echo -e "${YELLOW}${BOLD} DEBUG:${NC} ${_debug}"
fi
echo -e "${YELLOW}${ARROW} Headless mode is unattended — fix the above and re-run. Full contract:${NC}"
echo -e "${YELLOW}${ARROW} ./run.bash --help-run-headless${NC}\n"
} >&2
exit 1
}
# hl_is_cloud — true if this looks like a cloud-init-provisioned box, where a
# literal secret in the environment persists in user-data + the metadata service.
hl_is_cloud() {
[[ -d /var/lib/cloud/instance ]]
}
# hl_resolve_secret <BASENAME> <OUT_VAR> — resolve a secret from
# RUN_BASH_<BASENAME>_FILE (preferred) or the literal RUN_BASH_<BASENAME>, applying
# the V3.10 guardrails, and assign the secret bytes to the global named <OUT_VAR>
# via printf -v (NOT echoed — so it never lands in a captured/logged stdout, and so
# headless_fail runs in the caller's shell and exits cleanly). Empty when neither
# is set — the caller decides required-ness.
# both file+literal set -> fail fast (ambiguous; the literal still leaks)
# *_FILE set but unreadable -> fail fast (never fall back)
# literal on a cloud box -> fail fast (user-data / metadata persistence)
# literal elsewhere -> loud stderr warning, allowed
hl_resolve_secret() {
local _base="$1" _out="$2"
local _lit="RUN_BASH_${_base}" _file="RUN_BASH_${_base}_FILE"
local _litval="${!_lit:-}" _fileval="${!_file:-}"
local _result=""
if [[ -n "$_fileval" && -n "$_litval" ]]; then
headless_fail "Both ${_file} and ${_lit} are set (ambiguous, and the literal still leaks)." \
"Set exactly one — prefer the *_FILE form (the secret bytes never enter the environment)."
fi
if [[ -n "$_fileval" ]]; then
if [[ ! -r "$_fileval" ]]; then
headless_fail "${_file}=${_fileval} is not a readable file." \
"Point it at a 0600 file containing the secret; there is no fallback to a literal."
fi
# cat strips the trailing newline that echo>file / here-strings add.
_result="$(cat -- "$_fileval")"
elif [[ -n "$_litval" ]]; then
if hl_is_cloud; then
headless_fail "${_lit} is set as a LITERAL on a cloud-init box." \
"Literal secrets persist in cloud-init user-data + the metadata service (world-readable). Use ${_file} with an out-of-band-fetched 0600 file."
fi
echo -e "${YELLOW}${WARN} ${_lit} passed as a literal env value — it is inherited by child processes via /proc/PID/environ. Prefer ${_file}.${NC}" >&2
_result="$_litval"
fi
printf -v "$_out" '%s' "$_result"
}
# headless_preflight — validate every precondition + resolve every RUN_BASH_* value
# BEFORE any provisioning action, so an unattended run fails fast (never hangs) on a
# missing/unsafe input. Populates HL_* globals (non-exported: not visible to child
# processes via the environment) consumed by the execution path.
headless_preflight() {
echo -e "${CYAN}${INFO} Headless mode — validating RUN_BASH_* configuration${NC}" >&2
# Non-root: cloud-init runcmd is root; run.bash must run as the target user
# (matches the interactive root refusal). Checked here with headless guidance.
if [[ "$(whoami)" == "root" ]]; then
headless_fail "Headless run is executing as root." \
"Run as the non-root target user (cloud-init: sudo -u <user> -i env RUN_BASH_...=... ./run.bash)."
fi
# Required identity.
HL_USER_EMAIL="${RUN_BASH_USER_EMAIL:-}"
[[ -n "$HL_USER_EMAIL" ]] || headless_fail "RUN_BASH_USER_EMAIL is required." \
"Set it to the git email for this box, e.g. RUN_BASH_USER_EMAIL=name@example.com."
[[ "$HL_USER_EMAIL" == *@*.* ]] || headless_fail "RUN_BASH_USER_EMAIL='${HL_USER_EMAIL}' is not a valid email." \
"Use a form like name@example.com."
HL_USER_LOGIN="${RUN_BASH_USER_LOGIN:-$(whoami)}"
HL_USER_NAME="${RUN_BASH_USER_NAME:-$HL_USER_LOGIN}"
# GitHub is mandatory to CONFIGURE — accounts, or the literal 'none' to skip it.
HL_GITHUB_ACCOUNTS="${RUN_BASH_GITHUB_ACCOUNTS:-}"
[[ -n "$HL_GITHUB_ACCOUNTS" ]] || headless_fail "RUN_BASH_GITHUB_ACCOUNTS is required." \
"Set it to a single GitHub account (headless v1 requires GitHub configured)."
# v1 requires GitHub CONFIGURED. The 'configured empty' (RUN_BASH_GITHUB_ACCOUNTS=
# none) path is a planned follow-up: it must first fix two latent server-profile
# bugs (play-github-cli-multi.yml's ungated `gh --version`, play-lxc's git@ clone)
# that abort playbook-main on a no-GitHub box. Until then, fail fast rather than
# provision a box that would break at the playbook stage.
if [[ "$HL_GITHUB_ACCOUNTS" == "none" ]]; then
headless_fail "RUN_BASH_GITHUB_ACCOUNTS=none (GitHub-empty provisioning) is not supported in headless v1." \
"Provide a single GitHub account + RUN_BASH_GITHUB_TOKEN_FILE. (Empty-GitHub is a planned follow-up.)"
fi
# v1 supports a SINGLE account; multiple need one token file per alias (D5).
if [[ "$HL_GITHUB_ACCOUNTS" == *,* ]]; then
headless_fail "Multiple GitHub accounts ('${HL_GITHUB_ACCOUNTS}') are not supported in headless v1." \
"Use a single account."
fi
# Vault password: must be PROVIDED (either form, file preferred), NEVER
# auto-generated headless (V3.3/D6). Resolved here; the execution slice enforces
# required-when-vault-present.
hl_resolve_secret VAULT_PASSWORD HL_VAULT_PASSWORD
# Scoped token is required for non-interactive gh auth (`gh auth login --with-token`).
hl_resolve_secret GITHUB_TOKEN HL_GITHUB_TOKEN
[[ -n "$HL_GITHUB_TOKEN" ]] || headless_fail "RUN_BASH_GITHUB_TOKEN_FILE is required (headless v1 requires GitHub configured)." \
"Provide a 0600 file holding a scoped PAT (scopes: vars/github-required-scopes.yml + admin:public_key)."
hl_resolve_secret GITHUB_SSH_PASSPHRASE HL_GITHUB_SSH_PASSPHRASE
# Decision 6: the login SSH key stays passphrase-protected (this mirrors the
# interactive flow, which forbids an empty passphrase — run.bash:1278-1284).
# Headless v1 always configures GitHub and provisions the key non-interactively
# (ssh-agent + SSH_ASKPASS, D5/V3.12-V3.13), so the passphrase MUST be supplied up
# front — there is no TTY to prompt for it during the clone/pull later.
[[ -n "$HL_GITHUB_SSH_PASSPHRASE" ]] || headless_fail "RUN_BASH_GITHUB_SSH_PASSPHRASE_FILE is required (the login SSH key must stay passphrase-protected)." \
"Provide a 0600 file holding the SSH key passphrase (loaded via ssh-agent for the clone; never passed on argv to a child)."
# V3.10(e): drop any LITERAL secret env vars so children (dnf, gh, ansible) do not
# inherit them via /proc/PID/environ. The *_FILE path vars are not secret and stay.
unset RUN_BASH_VAULT_PASSWORD RUN_BASH_GITHUB_TOKEN RUN_BASH_GITHUB_SSH_PASSPHRASE
# NOPASSWD:ALL sudo (V3.7): the first direct sudo (dnf) runs with no TTY. Probe
# with -k so a cached timestamp cannot yield a false pass. Capture stderr (no
# error-hiding redirect) so the failure reason is shown. Last precondition — after
# the cheaper config checks so the most common mistake (missing env) reports first.
local _sudo_probe
if ! _sudo_probe="$(sudo -k -n true 2>&1)"; then
headless_fail "Passwordless (NOPASSWD:ALL) sudo is required (sudo: ${_sudo_probe:-a password is required})." \
"Grant NOPASSWD:ALL to this user (the default cloud user has it), or run interactively."
fi
echo -e "${GREEN}${CHECK} Headless preflight OK${NC} — user=${HL_USER_LOGIN} (${HL_USER_NAME}) email=${HL_USER_EMAIL} github=${HL_GITHUB_ACCOUNTS}" >&2
}
# hl_cleanup — EXIT-trap cleanup for a headless run: shred every 0600 secret file and,
# as a BACKSTOP, tear down the ssh-agent if it is still up (V3.11/V3.12). The agent is
# normally killed right after the last git op (hl_ssh_agent_stop); this only catches an
# abnormal exit. set -u-safe: every var is expanded with `:-` and the array with
# "${arr[@]:-}", so it is a harmless no-op on an interactive run or an early abort.
hl_cleanup() {
rm -f /tmp/.github_ssh_pp "${HL_SECRET_FILES[@]:-}"
if [[ -n "${HL_SSH_AGENT_PID:-}" ]]; then
local _o
if ! _o="$(SSH_AGENT_PID="$HL_SSH_AGENT_PID" ssh-agent -k 2>&1)"; then
echo " (cleanup) ssh-agent already gone: ${_o}" >&2
fi
fi
}
# hl_ssh_agent_start — start an ssh-agent and load the passphrase-protected login key
# (~/.ssh/id) non-interactively via a transient SSH_ASKPASS helper (D5/V3.13). There is
# NO file/stdin passphrase flag for ssh-add — SSH_ASKPASS (+SSH_ASKPASS_REQUIRE=force)
# is the ONLY non-interactive path. The passphrase is written to a 0600 file the helper
# reads at runtime (the helper carries only the non-secret PATH, never the passphrase),
# and both temp files are shredded by hl_cleanup. Fails LOUD on any error.
hl_ssh_agent_start() {
HL_SSH_PP_FILE="$(mktemp)" && chmod 600 "$HL_SSH_PP_FILE"
printf '%s' "$HL_GITHUB_SSH_PASSPHRASE" > "$HL_SSH_PP_FILE"
HL_ASKPASS="$(mktemp)" && chmod 700 "$HL_ASKPASS"
# Quoted heredoc: the helper body is written VERBATIM (the $HL_SSH_PP_FILE reference
# is resolved at askpass RUNTIME from the inherited env, not expanded here) — so the
# passphrase never enters the helper's own text, only the non-secret path does.
cat > "$HL_ASKPASS" <<'HL_ASKPASS_BODY'
#!/usr/bin/env bash
cat "$HL_SSH_PP_FILE"
HL_ASKPASS_BODY
HL_SECRET_FILES+=("$HL_SSH_PP_FILE" "$HL_ASKPASS")
export HL_SSH_PP_FILE
local _agent_out
if ! _agent_out="$(ssh-agent -s)"; then
hl_abort "ssh-agent start" "could not start ssh-agent to load the login SSH key" \
"ssh-agent -s failed: ${_agent_out}"
fi
eval "$_agent_out" # sets+exports SSH_AUTH_SOCK, SSH_AGENT_PID
HL_SSH_AGENT_PID="${SSH_AGENT_PID:-}"
local _add_out
if ! _add_out="$(SSH_ASKPASS="$HL_ASKPASS" SSH_ASKPASS_REQUIRE=force ssh-add ~/.ssh/id 2>&1)"; then
hl_abort "load login SSH key into ssh-agent" \
"the login SSH key (\$HOME/.ssh/id) could not be loaded — the supplied RUN_BASH_GITHUB_SSH_PASSPHRASE is probably wrong for this key" \
"ssh-add said: ${_add_out}"
fi
}
# hl_ssh_agent_stop — kill the ssh-agent immediately after the LAST git op (V3.12), so
# the unlocked key is not left reachable via $SSH_AUTH_SOCK across ansible-galaxy, the
# main playbook, optional playbooks, and reboot. hl_cleanup is only a backstop.
hl_ssh_agent_stop() {
[[ -n "${HL_SSH_AGENT_PID:-}" ]] || return 0
local _o
if ! _o="$(SSH_AGENT_PID="$HL_SSH_AGENT_PID" ssh-agent -k 2>&1)"; then
warning "ssh-agent teardown returned non-zero (agent may already be gone): ${_o}"
fi
unset SSH_AUTH_SOCK SSH_AGENT_PID HL_SSH_AGENT_PID
}
# hl_pull_config_source <localhost_yml> <hosts/name.yml> — headless: pull a saved
# config from the PRIVATE per-user config repo (RUN_BASH_CONFIG_SOURCE path). Refuses
# a non-private repo (localhost.yml carries PII + the vault) and fails LOUD if the repo
# or file is missing. Called only when RUN_BASH_CONFIG_SOURCE is set and != none.
hl_pull_config_source() {
local yml="$1" path="$2"
local repo="${primary_gh_username}/fedora-desktop-config" _priv _content
if ! _priv="$(gh api "repos/${repo}" --jq '.private' 2>&1)"; then
hl_abort "pull config source" \
"config repo github.com/${repo} not found or not accessible" \
"gh said: ${_priv}; set RUN_BASH_CONFIG_SOURCE=none to configure fresh from RUN_BASH_* instead"
fi
if [[ "$_priv" != "true" ]]; then
hl_abort "pull config source" \
"config repo github.com/${repo} is NOT private (.private='${_priv}') — it would hold PII + your Ansible vault" \
"make it private (gh repo edit ${repo} --visibility private), or use RUN_BASH_CONFIG_SOURCE=none"
fi
if ! _content="$(gh api "repos/${repo}/contents/${path}" --jq '.content' 2>&1)"; then
hl_abort "pull config source" \
"config file '${path}' not found in github.com/${repo}" \
"gh said: ${_content}; set RUN_BASH_CONFIG_SOURCE to a valid hosts/<name>.yml or 'none'"
fi
printf '%s' "$_content" | base64 -d > "$yml"
success "Headless: pulled config ${path} from github.com/${repo}"
}
# hl_write_localhost_yml <localhost_yml> — headless replacement for the interactive
# config-import menu. Idempotent: keeps an already-configured localhost.yml. Otherwise
# pulls RUN_BASH_CONFIG_SOURCE from the private config repo, or (the default 'none')
# writes a FRESH localhost.yml from RUN_BASH_* identity + RUN_BASH_GITHUB_ACCOUNTS.
hl_write_localhost_yml() {
local yml="$1"
if [[ -f "$yml" ]] && grep -qE '(!vault|github_accounts)' "$yml"; then
info "Headless: keeping existing configured localhost.yml"
return 0
fi
local src="${RUN_BASH_CONFIG_SOURCE:-none}"
if [[ -n "$src" && "$src" != "none" ]]; then
info "Headless: importing saved config '${src}' from the config repo"
hl_pull_config_source "$yml" "$src"
return 0
fi
info "Headless: writing fresh localhost.yml (identity + github_accounts)"
local _alias _user
if [[ "$HL_GITHUB_ACCOUNTS" == *:* ]]; then
_alias="${HL_GITHUB_ACCOUNTS%%:*}"; _user="${HL_GITHUB_ACCOUNTS##*:}"
else
_alias="personal"; _user="$HL_GITHUB_ACCOUNTS"
fi
{
printf 'user_login: "%s"\n' "$HL_USER_LOGIN"
printf 'user_name: "%s"\n' "$HL_USER_NAME"
printf 'user_email: "%s"\n' "$HL_USER_EMAIL"
printf '# GitHub CLI accounts — to add more later: scripts/gh-account-setup.bash --add=alias:username\n'
printf 'github_accounts:\n'
printf ' %s: "%s"\n' "$_alias" "$_user"
} > "$yml"
success "Headless: localhost.yml written (fresh)"
}
# hl_reconcile_vault <localhost_yml> <vault_pass_file> — headless vault reconciliation
# (D6): the password must be PROVIDED (RUN_BASH_VAULT_PASSWORD[_FILE], resolved in
# preflight into HL_VAULT_PASSWORD), verified against any encrypted values, and NEVER
# auto-generated over a !vault (that would silently orphan the encrypted data). A vault
# password is genuinely required because the github_ssh_passphrase is vault-encrypted
# into localhost.yml right after this. Every failure aborts LOUD.
hl_reconcile_vault() {
local yml="$1" vpf="$2" has_vault=false
if grep -qF '!vault' "$yml"; then has_vault=true; fi
if [[ -n "$HL_VAULT_PASSWORD" ]]; then
printf '%s' "$HL_VAULT_PASSWORD" > "$vpf"
chmod 600 "$vpf"
if [[ "$has_vault" == "true" ]]; then
if ! verify_vault_password "$HL_VAULT_PASSWORD" "$yml"; then
hl_abort "vault reconcile" \
"RUN_BASH_VAULT_PASSWORD does not decrypt the vault-encrypted values in localhost.yml" \
"check it matches the vault this config was encrypted with — headless never auto-generates over encrypted values (D6)"
fi
success "Headless: vault password verified against encrypted config"
else
success "Headless: vault password set"
fi
return 0
fi
# No password provided.
if [[ "$has_vault" == "true" ]]; then
if [[ -f "$vpf" && -s "$vpf" ]] && verify_vault_password "$(cat "$vpf")" "$yml"; then
success "Headless: existing vault-pass.secret verified against encrypted config"
else
hl_abort "vault reconcile" \
"localhost.yml has vault-encrypted values but no working vault password" \
"provide RUN_BASH_VAULT_PASSWORD_FILE matching the vault this config was encrypted with"
fi
elif [[ -f "$vpf" && -s "$vpf" ]]; then
success "Headless: using existing vault-pass.secret"
else
hl_abort "vault reconcile" \
"a vault password is required (github_ssh_passphrase is vault-encrypted) but RUN_BASH_VAULT_PASSWORD[_FILE] was not provided and no vault-pass.secret exists" \
"set RUN_BASH_VAULT_PASSWORD_FILE to a 0600 file holding the vault password"
fi
}
# hl_run_optional_playbooks — headless replacement for the interactive optional-playbook
# menu. Runs exactly the plays named in RUN_BASH_OPTIONAL_PLAYBOOKS (space/comma list of
# play-foo.yml | foo | play-foo), in order; 'none'/unset skips the whole section. The
# reserved token 'server-recommended' expands to the curated, generic dev/server bundle in
# playbooks/imports/optional/server-recommended.bundle (composes with explicit tokens).
# Any unknown name or failing play aborts LOUD (a server run must not silently under-provision).
hl_run_optional_playbooks() {
local spec="${RUN_BASH_OPTIONAL_PLAYBOOKS:-none}"
if [[ -z "$spec" || "$spec" == "none" ]]; then
info "Headless: RUN_BASH_OPTIONAL_PLAYBOOKS=none — skipping optional playbooks"
return 0
fi
if [[ ! -d ~/Projects/fedora-desktop ]]; then
hl_abort "optional playbooks" "$HOME/Projects/fedora-desktop not found — the repo was not cloned" \
"run the full headless install (it clones the repo) before requesting optional playbooks"
fi
cd ~/Projects/fedora-desktop || hl_abort "optional playbooks" "cannot cd into ~/Projects/fedora-desktop" "check the clone succeeded"
local -a _all_optional
mapfile -t _all_optional < <(find playbooks/imports/optional -name "*.yml" -type f | sort)
local -a _reqs
IFS=' ,' read -ra _reqs <<< "$spec"
# Expand the server-recommended bundle keyword (Plan 00065 Phase 5) into its
# manifest-listed plays, then de-dup so a play named by both the bundle and an
# explicit token only runs once. Expansion happens BEFORE the per-token resolution
# loop below, so composing with explicit tokens ("server-recommended play-ddev.yml")
# and the unknown-token abort are both inherited for free — nothing below changes.
local _bundle_file="playbooks/imports/optional/server-recommended.bundle"
local -a _expanded=()
local req _line
for req in "${_reqs[@]}"; do
[[ -z "$req" ]] && continue
if [[ "$req" == "server-recommended" ]]; then
if [[ ! -f "$_bundle_file" ]]; then
hl_abort "optional playbooks" \
"RUN_BASH_OPTIONAL_PLAYBOOKS requested 'server-recommended' but ${_bundle_file} is missing" \
"the ~/Projects/fedora-desktop checkout may be stale/corrupt — re-clone, or drop 'server-recommended' from the list"
fi
# `|| [[ -n "$_line" ]]` so a final manifest line with NO trailing newline is
# still processed — a bare `while read` returns nonzero at a no-newline EOF and
# would silently DROP that last play (silent under-provisioning, fail-fast rule #1).
while IFS= read -r _line || [[ -n "$_line" ]]; do
[[ -z "$_line" || "$_line" == \#* ]] && continue
_expanded+=("$_line")
done < "$_bundle_file"
else
_expanded+=("$req")
fi
done
# De-dup, preserving first-seen order.
local -a _reqs_deduped=()
local -A _seen=()
for req in "${_expanded[@]}"; do
[[ -n "${_seen[$req]:-}" ]] && continue
_seen[$req]=1
_reqs_deduped+=("$req")
done
_reqs=("${_reqs_deduped[@]}")
local pb base found name
for req in "${_reqs[@]}"; do
[[ -z "$req" ]] && continue
found=""
for pb in "${_all_optional[@]}"; do
base="$(basename "$pb")"
if [[ "$base" == "$req" || "$base" == "$req.yml" || "$base" == "play-${req}.yml" ]]; then
found="$pb"; break
fi
done
if [[ -z "$found" ]]; then
hl_abort "optional playbooks" "requested optional playbook '${req}' not found under playbooks/imports/optional/" \
"use an exact name like play-docker.yml (or docker), or set RUN_BASH_OPTIONAL_PLAYBOOKS=none"
fi
name="$(basename "$found" .yml)"
info "Headless: running optional playbook ${name}"
if ! "$found"; then
hl_abort "optional playbook ${name}" "${found} FAILED" \
"scroll up for the Ansible output; fix it, drop it from RUN_BASH_OPTIONAL_PLAYBOOKS, or set =none"
fi
success "Headless: optional playbook ${name} complete"
done
}
# ── main() — the entire executable body ──────────────────────────────────────
# B5: wrapping everything in main() (and only calling it on the last line via
# `( main "$@" )`) guarantees the WHOLE file is parsed before any command runs.
# This matters when run.bash is executed as a real file (kickstart / dev): the
# `git pull` steps below can rewrite run.bash on disk, and an un-wrapped script
# is still being streamed byte-by-byte by bash, so a rewrite mid-run corrupts the
# remaining offsets. With main(), bash has already read+parsed the whole file, so
# a pull cannot affect the in-flight run. The call is wrapped in its own subshell
# so set -e / IFS / trap / exit stay contained (H4 sourced-shell safety).
main() {
set -e
set -u
set -o pipefail
IFS=$'\n\t'
# Safety net: always clean up sensitive temp files on exit.
# HL_SECRET_FILES holds any 0600 secret files a headless run must shred on ANY
# exit path (V3.4/V3.11). Initialised empty BEFORE the trap so the trap is
# set -u-safe even when no headless secret files exist (empty-GitHub path / an
# early abort before the files are learned) — a "${arr[@]:-}" expansion of an
# empty array is a harmless no-op for rm -f, never an unbound-variable error.
HL_SECRET_FILES=()
HL_SSH_AGENT_PID="" # set by hl_ssh_agent_start; kept empty so hl_cleanup is set -u-safe
trap hl_cleanup EXIT
# Flags
OPTIONAL_ONLY=false
# Headless / unattended mode (Plan 00063) — provision a Fedora Server or Cloud box
# with no interactive prompts, driven by RUN_BASH_* env vars. Tri-state:
# HEADLESS="" -> not yet decided (auto-detect below)
# HEADLESS=true -> forced on (--headless, or RUN_BASH_HEADLESS=1)
# HEADLESS=false -> forced off (--interactive)
# See ./run.bash --help-run-headless for the full env contract.
HEADLESS=""
for _arg in "$@"; do
case "$_arg" in
--help|-h)
cat <<'USAGE'
Usage: ./run.bash [OPTIONS]
Fedora Desktop / Server / Cloud Configuration Installer
Options:
--optional-only Skip core setup, jump straight to optional playbook menu
--headless Force unattended mode (no prompts); config from RUN_BASH_* env
--interactive Force interactive mode even with no TTY / RUN_BASH_* set
-h, --help Show this help message
--help-run-headless Deep-dive: unattended/IaC provisioning (server & cloud)
Interactive first run (desktop):
./run.bash Full install (system deps, SSH, GitHub, Ansible,
main playbook, then optional playbooks menu)
Subsequent runs:
./run.bash --optional-only Re-run only the optional playbooks menu
(useful for adding components after initial setup)
Headless (server / cloud) — provision unattended from RUN_BASH_* env vars:
RUN_BASH_HEADLESS=1 RUN_BASH_USER_EMAIL=... RUN_BASH_GITHUB_ACCOUNTS=... \
./run.bash # full env contract: ./run.bash --help-run-headless
Desktop vs. server/cloud is auto-detected by the Ansible layer
(systemctl get-default -> graphical.target = desktop, else server); Fedora Cloud
resolves to the server subset (no GNOME). Override with
RUN_BASH_PROVISIONING_PROFILE=desktop|server.
Requirements:
- Fedora Linux (version must match the branch)
- Network connectivity (GitHub, DNF repos)
- Must NOT be run as root (uses sudo internally; headless: run as the non-root
target user with NOPASSWD sudo)
USAGE
exit 0
;;
--help-run-headless)
cat <<'USAGE'
run.bash — HEADLESS / UNATTENDED provisioning (server & cloud, IaC)
===================================================================
Provision a headless Fedora Server or Cloud box end-to-end with ZERO interactive
prompts, driven entirely by RUN_BASH_* environment variables. run.bash runs on the
box it provisions (connection: local) and self-updates the repo, so a headless run
always provisions the branch-latest source. The Ansible layer auto-detects the
server profile and skips all GNOME/desktop plays (Plan 00061); Fedora Cloud is
treated as a server (no new scope needed).
TRIGGER
Headless is ON when any of:
* --headless flag, or RUN_BASH_HEADLESS=1
* stdin is not a TTY AND >=1 RUN_BASH_* config var is set
Force OFF with --interactive. (Piped-stdin smoke tests: pass --interactive or
set no RUN_BASH_* to avoid tripping headless.)
PRECONDITIONS (fail fast if unmet — never hangs)
* NOPASSWD:ALL sudo (the default cloud user has it; a password-sudo Server does
not — configure NOPASSWD or run interactively).
* Run as the NON-root target user (cloud-init runcmd is root; drop to the user).
* GitHub is mandatory in headless v1: set RUN_BASH_GITHUB_ACCOUNTS to a single
account AND provide RUN_BASH_GITHUB_TOKEN_FILE AND
RUN_BASH_GITHUB_SSH_PASSPHRASE_FILE (the login SSH key stays passphrase-
protected). Unset => fail fast. (The 'none' / GitHub-empty path is a planned
follow-up, not yet supported.)
NON-SECRET CONFIG (plain RUN_BASH_* env)
RUN_BASH_HEADLESS=1 Force headless.
RUN_BASH_USER_EMAIL=... Git email. (REQUIRED)
RUN_BASH_GITHUB_ACCOUNTS=... Single gh username (v1). ('none' is a planned
follow-up, not yet supported.) (REQUIRED)
RUN_BASH_USER_LOGIN=... System login. (default: current user)
RUN_BASH_USER_NAME=... Full name. (default: = login)
RUN_BASH_HOSTNAME=... Set hostname when box is still 'fedora'.
RUN_BASH_CONFIG_SOURCE=... Config-repo host file to import, or 'none'.
RUN_BASH_PROVISIONING_PROFILE= Force desktop|server (default: auto-detect).
RUN_BASH_OPTIONAL_PLAYBOOKS=... Space/comma list of optional plays, or 'none'.
'server-recommended' expands to a curated, generic
dev/server bundle (see
playbooks/imports/optional/server-recommended.bundle);
combine with explicit plays, e.g.
"server-recommended play-ddev.yml".
RUN_BASH_RESTORE_PROJECTS=0|1 Restore projects from config manifest.
RUN_BASH_REBOOT=0|1 Reboot at end.
SECRETS — prefer 0600 FILE POINTERS (recommended), literal env supported but risky
RUN_BASH_VAULT_PASSWORD_FILE=/path Ansible vault password (file).
RUN_BASH_GITHUB_TOKEN_FILE=/path Scoped GitHub PAT (file); REQUIRED
in headless v1 (GitHub is mandatory).
RUN_BASH_GITHUB_SSH_PASSPHRASE_FILE=/path SSH key passphrase (file); REQUIRED
in v1 (the login key stays passphrase-
protected, loaded via ssh-agent).
Literal equivalents (RUN_BASH_VAULT_PASSWORD, _GITHUB_TOKEN,
_GITHUB_SSH_PASSPHRASE) are accepted but:
* REFUSED on a detected cloud box (cloud-init user-data persists them in the
metadata service, world-readable indefinitely) -> use the *_FILE form.
* warned loudly otherwise; setting BOTH a literal and its *_FILE is an error.
The *_FILE form is best: the secret bytes never enter the environment,
process listings, or cloud-init user-data.
GitHub token scope: the full vars/github-required-scopes.yml set + admin:public_key.
GITHUB (headless v1 — always CONFIGURED)
RUN_BASH_GITHUB_ACCOUNTS=<user> -> full GitHub setup via the scoped token file
(single account in v1). This is the ONLY supported headless path today.
The GitHub-empty path (RUN_BASH_GITHUB_ACCOUNTS=none -> HTTPS-only public clone,
no token/SSH key) is a planned follow-up: it is currently BLOCKED by two
latent server-profile playbook bugs, so v1 fails fast on 'none' rather than
provision a box that would break at the playbook stage.
CANONICAL INVOCATION (run as the non-root user)
The single supported headless provision — branch-latest repo, full setup:
RUN_BASH_HEADLESS=1 \
RUN_BASH_USER_EMAIL=name@example.com \
RUN_BASH_GITHUB_ACCOUNTS=<gh-username> \
RUN_BASH_GITHUB_TOKEN_FILE=/run/secrets/gh-token \
RUN_BASH_GITHUB_SSH_PASSPHRASE_FILE=/run/secrets/ssh-pass \
RUN_BASH_VAULT_PASSWORD_FILE=/run/secrets/vault-pass \
./run.bash
CLOUD-INIT (Fedora Cloud) — fetch secrets OUT-OF-BAND, never in write_files
write_files embeds content INSIDE user-data (served by the metadata service
forever) — so NEVER put secret bytes there. Fetch them out-of-band inside
runcmd, e.g.:
runcmd:
- [ sh, -c, 'aws secretsmanager get-secret-value --secret-id vault
--query SecretString --output text > /run/secrets/vault-pass' ]
- [ sh, -c, 'aws secretsmanager get-secret-value --secret-id gh-token
--query SecretString --output text > /run/secrets/gh-token' ]
- [ sh, -c, 'sudo -u <user> -i env RUN_BASH_HEADLESS=1
RUN_BASH_USER_EMAIL=name@example.com RUN_BASH_GITHUB_ACCOUNTS=<gh-username>
RUN_BASH_GITHUB_TOKEN_FILE=/run/secrets/gh-token
RUN_BASH_VAULT_PASSWORD_FILE=/run/secrets/vault-pass
/home/<user>/run.bash' ]
Replace <user> with the box's non-root user (Fedora Cloud's default distro user).
/run/secrets is tmpfs (RAM-backed, wiped on reboot). Pin the run.bash source to
a commit SHA (not HEAD) when fetching it, and inspect before running.
FAIL-FAST GUARANTEE
Any missing required value or unmet precondition aborts with a clear message
naming the exact fix — a headless run never hangs waiting on a prompt, and a
failed main playbook exits non-zero (never reports success).
USAGE
exit 0
;;
--headless)
HEADLESS=true
;;
--interactive)
HEADLESS=false
;;
--optional-only)
OPTIONAL_ONLY=true
;;
*)
echo "Unknown option: $_arg" >&2
echo "Run './run.bash --help' for usage" >&2
exit 1
;;
esac
done
# Resolve the headless auto-detect when neither --headless nor --interactive forced
# it. RUN_BASH_HEADLESS wins first; otherwise headless requires BOTH no-TTY-on-stdin
# AND at least one RUN_BASH_* config var (so an accidental desktop pipe with no
# RUN_BASH_* never silently goes headless).
if [[ -z "$HEADLESS" ]]; then
case "${RUN_BASH_HEADLESS:-}" in
1|true|yes|on)
HEADLESS=true
;;
0|false|no|off)
HEADLESS=false
;;
*)
# Any RUN_BASH_* config var set, excluding the script's own VERSION constant?
_rb_has_cfg=false
while IFS= read -r _rb_v; do
if [[ "$_rb_v" != "RUN_BASH_VERSION" ]]; then
_rb_has_cfg=true
break
fi
done < <(compgen -v | grep -E '^RUN_BASH_')
if [[ ! -t 0 && "$_rb_has_cfg" == "true" ]]; then
HEADLESS=true
else
HEADLESS=false
fi
unset _rb_has_cfg _rb_v
;;
esac
fi
# Headless: validate + resolve all RUN_BASH_* input up front (fail fast, never hang)
# BEFORE any provisioning action. On success the run then flows through the SAME body
# as the interactive path — every interactive point below has a headless branch that
# uses the resolved HL_*/RUN_BASH_* values, and the shared prompt helpers hard-fail
# LOUD (hl_abort) if a headless run ever reaches an un-neutralised prompt.
if [[ "$HEADLESS" == "true" ]]; then
headless_preflight
echo -e "\n${YELLOW}${ARROW} run.bash v${RUN_BASH_VERSION}: headless preflight OK — provisioning unattended.${NC}" >&2
fi
## Step counter
# STEP_TOTAL is derived by counting the title() calls in this very script, so it
# can never drift out of sync with the actual number of steps (the old hardcoded
# 13 lagged the real 17 and produced "14/13"). When the script is streamed
# (README install: `source <(curl ...)`), BASH_SOURCE is a consumed pipe that
# cannot be re-read, so we fall back to the known count.
STEP_CURRENT=0
STEP_TOTAL=17 # fallback for the streamed (curl) install path
_run_bash_self="${BASH_SOURCE[0]:-}"
if [[ -f "$_run_bash_self" && -r "$_run_bash_self" ]]; then
if _run_bash_steps=$(grep -cE '^[[:space:]]*title[[:space:]]+"' "$_run_bash_self"); then
if [[ "$_run_bash_steps" =~ ^[0-9]+$ ]] && (( _run_bash_steps > 0 )); then
STEP_TOTAL="$_run_bash_steps"
fi
fi
unset _run_bash_steps
fi
unset _run_bash_self
# M4: under --optional-only only ONE title() is reachable ("System Reboot") — the
# whole core-setup block (every other title) is skipped. Show [1/1], not [1/17].
if [[ "${OPTIONAL_ONLY:-}" == "true" ]]; then
STEP_TOTAL=1
fi
## Assertions
if [[ "$(whoami)" == "root" ]];
then
echo -e "\n${RED}${BOLD}${CROSS} ERROR${NC}"
echo -e "${RED}Please do not run this as root${NC}\n"
echo -e "Simply run as your normal user\n"
exit 1
fi
# Header
# Defect 4: `clear` exits 1 ("TERM environment variable not set") in a
# non-interactive context, which aborts the run under set -e. Only clear when
# stdout is a real terminal — the [[ -t 1 ]] guard keeps fail-fast intact while
# skipping the clear when there is no tty.
[[ -t 1 ]] && clear
echo -e "${BLUE}${BOLD}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}${BOLD}║ FEDORA DESKTOP CONFIGURATION INSTALLER ║${NC}"
echo -e "${BLUE}${BOLD}╚══════════════════════════════════════════════════════════════╝${NC}"
echo -e " ${CYAN}run.bash v${RUN_BASH_VERSION}${NC}\n"
# Detect actual Fedora version (version check happens after repo clone)
fedora_version=$(grep "^VERSION_ID=" /etc/os-release | cut -d= -f2)
echo -e "${CYAN}${INFO} Running on Fedora ${fedora_version}${NC}"
## Functions
title(){
STEP_CURRENT=$(( STEP_CURRENT + 1 ))
echo -e "\n${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${CYAN}${BOLD}[$STEP_CURRENT/$STEP_TOTAL]${NC} ${BOLD}$1${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}
completed(){
echo -e "${GREEN}${CHECK} Completed successfully${NC}"
}
info(){
echo -e "${CYAN}${INFO} $1${NC}"
}
success(){
echo -e "${GREEN}${CHECK} $1${NC}"
}
warning(){
echo -e "${YELLOW}${WARN} $1${NC}"
}
error(){
echo -e "${RED}${CROSS} $1${NC}"
}
wait_for_network(){
info "Checking network connectivity..."
local attempts=0
local max_attempts=30
while ! curl --silent --show-error --max-time 5 --output /dev/null https://github.com; do
attempts=$((attempts + 1))
if [[ $attempts -ge $max_attempts ]]; then
echo -e "${RED}${CROSS} ERROR: No network connectivity after $max_attempts attempts${NC}" >&2
echo -e "${YELLOW}${INFO} Please check your network connection and re-run this script${NC}" >&2
exit 1
fi
echo -e "${YELLOW}${WARN} Network not ready (attempt $attempts/$max_attempts) — retrying in 2s...${NC}"
sleep 2
done
success "Network connectivity confirmed"
}
# Abort the script if the given repo has uncommitted changes. run.bash
# does `git pull` at two points and a dirty working tree causes the pull
# to fail with an unhelpful error. Fail fast with a clear remediation.
assert_clean_worktree(){
local dir="$1"
local dirty
dirty="$(git -C "$dir" status --porcelain)"
if [[ -n "$dirty" ]]; then
error "Working tree at $dir has uncommitted changes"
echo -e "${YELLOW}${ARROW} run.bash needs a clean working tree before pulling updates.${NC}"
echo -e "${YELLOW}${ARROW} Inspect:${NC} ${BOLD}cd $dir && git status${NC}"
echo -e "${YELLOW}${ARROW} Resolve by committing:${NC}"
echo -e " ${BOLD}git add -p && git commit${NC}"
echo -e "${YELLOW}${ARROW} Or by temporarily stashing (remember to restore afterwards):${NC}"
echo -e " ${BOLD}git stash push -m 'pre-run.bash' && ./run.bash && git stash pop${NC}"
exit 1
fi
}
# confirm <msg> [default] — y/n confirmation with a visible safe default.
# default=y → prompt renders (Y/n), Enter accepts (returns 0).
# default=n → prompt renders (y/N), Enter declines (returns 1).
# default omitted → no Enter default; Enter re-prompts (back-compat for any
# caller that wants an explicit keypress).
# Use default=y for benign continues and value confirmations; default=n for
# destructive actions (reboot, posting a PUBLIC issue, running untested code).
# Invalid keys re-prompt with what to press — confirm() never exits the run.
confirm(){
local msg="$1"
# Headless backstop (fail LOUD, never hang): a correctly-configured headless run
# supplies every decision via RUN_BASH_*, so it must NEVER reach an interactive
# yes/no prompt. If it does, a call site was not neutralised — abort loudly rather
# than block forever waiting on a TTY that isn't there.
[[ "${HEADLESS:-}" == "true" ]] && hl_abort "unattended yes/no prompt reached" \
"headless hit a confirmation prompt: \"${msg}\"" \
"this decision has no RUN_BASH_* input wired up (a run.bash bug) — report it, or run interactively"
local default="${2:-}"
local yn=""
local hint
case "$default" in
y) hint="(Y/n)" ;;
n) hint="(y/N)" ;;
*) hint="(y/n)" ;;
esac
echo
echo -e "${YELLOW}${ARROW}${NC} $msg ${BOLD}${hint}${NC}"
while true; do
read -rp " Your choice: " yn
# Enter with a configured default takes that default.
if [[ -z "$yn" ]]; then
case "$default" in
y) echo -e "${GREEN}${CHECK} Confirmed${NC}\n"; return 0 ;;
n) echo -e "${YELLOW}${INFO} Skipped${NC}\n"; return 1 ;;
*) echo -e " ${RED}${CROSS} Please press 'y' for yes or 'n' for no${NC}"; continue ;;
esac
fi
case "${yn,,}" in
y|yes) echo -e "${GREEN}${CHECK} Confirmed${NC}\n"; return 0 ;;
n|no) echo -e "${YELLOW}${INFO} Skipped${NC}\n"; return 1 ;;
*) echo -e " ${RED}${CROSS} Invalid input '${yn}'. Enter 'y' for yes or 'n' for no ${BOLD}${hint}${NC}" ;;
esac
done
}
# Back up a config file with timestamp. No-op if file doesn't exist.
backup_config(){
local config_file="$1"
if [[ ! -f "$config_file" ]]; then
return 0
fi
local backup_file
backup_file="${config_file}.backup.$(date +%Y%m%d-%H%M%S)"
cp "$config_file" "$backup_file"
success "Config backed up to $(basename "$backup_file")"
}
# Selective config import: decode saved config, show top-level YAML keys,
# let user exclude some, write filtered result to output file.
# Sets _excluded_keys (comma-separated) for the caller to check.
selective_config_import(){
local raw_b64="$1"
local output_file="$2"
local temp_config
local temp_excluded
temp_config=$(mktemp)
temp_excluded=$(mktemp)
printf '%s' "$raw_b64" | base64 -d > "$temp_config"
python3 scripts/config_merge.py selective "$temp_config" "$output_file" "$temp_excluded"
_excluded_keys=""
if [[ -s "$temp_excluded" ]]; then
_excluded_keys=$(cat "$temp_excluded")
fi
rm -f "$temp_config" "$temp_excluded"
}
# Merge remote config into local config interactively.
# Shows per-key diff: unchanged keys auto-keep, changed keys prompt L/R,
# new remote keys prompt A/S. Local-only keys always kept.
merge_config_import(){
local raw_b64="$1"
local local_file="$2"
local temp_remote
temp_remote=$(mktemp)
printf '%s' "$raw_b64" | base64 -d > "$temp_remote"
python3 scripts/config_merge.py merge "$local_file" "$temp_remote" "$local_file"
rm -f "$temp_remote"
}
# Push local config to the per-host path in the config repo.
# Uses GitHub Contents API (create or update).
push_config_to_repo(){
local config_file="$1"
local repo="$2"
local path="$3"
local host_label="$4"
local content_b64
content_b64=$(base64 -w0 "$config_file")
# Get existing file SHA if updating (not needed for first create)
local existing_sha=""
if existing_sha=$(gh api "repos/${repo}/contents/${path}" --jq '.sha' 2>/dev/null); then
: # SHA retrieved for update
else
existing_sha="" # File doesn't exist yet — will create
fi
local -a api_args=(
--method PUT
--field "message=Update config from ${host_label}"
--field "content=${content_b64}"
)
if [[ -n "$existing_sha" ]]; then
api_args+=(--field "sha=${existing_sha}")
fi
gh api "repos/${repo}/contents/${path}" "${api_args[@]}" --silent
}
# Prompt for GitHub username(s) and write github_accounts YAML block to stdout.
# All user-facing prompts go to stderr so stdout is clean YAML for redirection.
prompt_github_accounts_yaml(){
# Headless backstop (fail LOUD, never hang) — see confirm(). Headless builds the
# github_accounts block from RUN_BASH_GITHUB_ACCOUNTS, so it must never prompt here.
[[ "${HEADLESS:-}" == "true" ]] && hl_abort "unattended GitHub-accounts prompt reached" \
"headless reached the interactive GitHub username prompt" \
"the headless path must build github_accounts from RUN_BASH_GITHUB_ACCOUNTS — a missing wiring here is a run.bash bug"
echo -e "\n${CYAN}${ARROW}${NC} Enter your GitHub username(s)" 1>&2
echo -e " These are the usernames you log into github.com with." 1>&2
echo -e " For multiple accounts, prefix each with a short alias and colon." 1>&2
echo -e "" 1>&2
echo -e " ${BOLD}One account:${NC} johndoe" 1>&2
echo -e " ${BOLD}Multiple accounts:${NC} personal:johndoe,work:johndoe-corp" 1>&2
local github_accounts_raw _account_count _has_unaliased _alias _username _valid
# Re-prompt until the entry validates — a malformed accounts string must NOT
# kill the run (it used to `exit 1` on a missing alias or a duplicate alias).
while true; do
github_accounts_raw="$(promptForValue 'GitHub username(s), comma separated')"
# M3: grep -c exits 1 (and prints 0) when there are no non-blank lines, e.g.
# the user typed only commas/spaces. Under set -e + pipefail that non-zero
# would kill the installer. Capture without aborting so the validation below
# re-prompts instead.
if ! _account_count=$(printf '%s' "$github_accounts_raw" | tr ',' '\n' | grep -c '[^[:space:]]'); then
_account_count=0
fi
# Defect 2: comma/space-only input (e.g. ',' or ',,,') yields zero real
# entries. Without this guard it would pass validation and write a bare
# `github_accounts:` map with no entries, then gh-account-setup.bash would run
# against an empty mapping. Re-prompt for at least one real account.
if (( _account_count < 1 )); then
error "Enter at least one account as alias:username (or a bare username)" 1>&2
echo -e " You entered: ${BOLD}${github_accounts_raw}${NC}" 1>&2
continue
fi
_has_unaliased=false
while IFS= read -r pair; do
pair="${pair// /}"
[[ -z "$pair" ]] && continue
if [[ "$pair" != *":"* ]]; then
_has_unaliased=true
fi
done < <(printf '%s\n' "$github_accounts_raw" | tr ',' '\n')
if [[ "$_has_unaliased" == "true" ]] && [[ "$_account_count" -gt 1 ]]; then
error "Multiple accounts require aliases. Use format: alias:username,alias:username" 1>&2
echo -e " You entered: ${BOLD}${github_accounts_raw}${NC}" 1>&2
echo -e " Example: ${BOLD}personal:user1,work:user2${NC}" 1>&2
continue
fi
_valid=true
declare -A _seen_aliases=()
while IFS= read -r pair; do
pair="${pair// /}"
if [[ "$pair" == *":"* ]]; then
_alias="${pair%%:*}"
_username="${pair##*:}"
elif [[ -n "$pair" ]]; then
_alias="personal"
_username="$pair"
else
continue
fi
# Defect 1: an empty alias (e.g. ':johndoe' or 'a,:b') would make
# ${_seen_aliases[$_alias]:-} a bash 5.2 'bad array subscript' FATAL error
# that kills the shell even inside this if. Reject and re-prompt instead.
if [[ -z "$_alias" ]]; then
error "Empty alias in '${pair}' — use the format alias:username" 1>&2
_valid=false
break
fi
# Defect 2 (username side): an entry like 'alias:' has no username. Reject.
if [[ -z "$_username" ]]; then
error "Empty username in '${pair}' — use the format alias:username" 1>&2