-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrun.bash
More file actions
executable file
·1277 lines (1130 loc) · 46.3 KB
/
run.bash
File metadata and controls
executable file
·1277 lines (1130 loc) · 46.3 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.0.14" # Bypass git() wrapper with `command git` for pulls (set -e safety)
set -e
set -u
set -o pipefail
IFS=$'\n\t'
# Safety net: always clean up sensitive temp files on exit
trap 'rm -f /tmp/.github_ssh_pp' EXIT
# Flags
OPTIONAL_ONLY=false
for _arg in "$@"; do
if [[ "$_arg" == "--optional-only" ]]; then
OPTIONAL_ONLY=true
fi
done
## Colors and formatting
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="🐛"
## Step counter
STEP_CURRENT=0
STEP_TOTAL=13
## 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
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++)) || true
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(){
local msg="$1"
local yn=""
echo
echo -e "${YELLOW}${ARROW}${NC} $msg"
while true; do
read -rsp " Press 'y' to confirm, 'n' to skip: " -n 1 yn
echo
if [[ "$yn" == "y" ]]; then
echo -e "${GREEN}${CHECK} Confirmed${NC}\n"
return 0
elif [[ "$yn" == "n" ]]; then
echo -e "${YELLOW}${INFO} Skipped${NC}\n"
return 1
else
echo -e "${RED}${CROSS} Invalid input. Please press 'y' or 'n'${NC}"
fi
done
}
# Function to sanitize sensitive data from error logs
sanitize_error_log(){
local log_content="$1"
local sanitized="$log_content"
# Remove potential API keys, tokens, and secrets
sanitized=$(echo "$sanitized" | sed -E 's/(api[_-]?key|token|secret|password|passwd|pwd)[[:space:]]*[:=][[:space:]]*[^[:space:]]+/\1=***REDACTED***/gi')
# Remove email addresses
sanitized=$(echo "$sanitized" | sed -E 's/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/***EMAIL***/g')
# Remove IP addresses
sanitized=$(echo "$sanitized" | sed -E 's/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/***IP***/g')
# Remove SSH key fingerprints
sanitized=$(echo "$sanitized" | sed -E 's/SHA256:[a-zA-Z0-9+/]+/SHA256:***FINGERPRINT***/g')
# Remove home directory paths with actual username
local current_user
current_user="$(whoami)"
# shellcheck disable=SC2001
sanitized=$(echo "$sanitized" | sed "s|/home/$current_user|/home/***USER***|g")
# Remove vault passwords and encrypted content
# shellcheck disable=SC2016
sanitized=$(echo "$sanitized" | sed -E 's/\$ANSIBLE_VAULT;[^[:space:]]+/\$ANSIBLE_VAULT;***ENCRYPTED***/g')
echo "$sanitized"
}
# Function to check if Claude Code is available for enhanced sanitization
check_claude_code(){
if command -v claude &> /dev/null; then
return 0
else
return 1
fi
}
# Function to create GitHub issue for failed playbook
create_github_issue(){
local playbook_name="$1"
local exit_code="$2"
local error_log=""
echo -e "\n${YELLOW}${BOLD}${BUG} Playbook Failure Detected${NC}"
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
# Check if we're in the git repo and have gh CLI
if ! git rev-parse --git-dir > /dev/null 2>&1; then
error "Not in a git repository. Cannot create issue."
return 1
fi
if ! command -v gh &> /dev/null; then
error "GitHub CLI not found. Cannot create issue."
return 1
fi
# Get system information
local fedora_version branch commit hostname kernel
fedora_version=$(grep "^VERSION_ID=" /etc/os-release | cut -d= -f2)
branch=$(git branch --show-current)
commit=$(git rev-parse --short HEAD)
hostname=$(hostname)
kernel=$(uname -r)
# Ask user to paste error output
echo -e "\n${CYAN}${ARROW} Please copy and paste the relevant error output from above${NC}"
echo -e "${YELLOW}${INFO} Paste the error, then press Ctrl+D when done:${NC}\n"
error_log=$(cat)
# Sanitize the error log
info "Sanitizing error log for sensitive data..."
local sanitized_log
sanitized_log=$(sanitize_error_log "$error_log")
# If Claude Code is available, use it for enhanced sanitization
if check_claude_code; then
info "Using Claude Code for enhanced sensitive data removal..."
local temp_file
temp_file=$(mktemp)
echo "$sanitized_log" > "$temp_file"
# Ask Claude to sanitize the log further
local claude_sanitized
claude_sanitized=$(claude "Please remove any potentially sensitive information from this error log including passwords, API keys, tokens, personal data, private URLs, or system-specific paths that shouldn't be shared publicly. Return ONLY the sanitized version of the log, preserving the error messages and structure but with sensitive data replaced with placeholders like ***REDACTED***:\n\n$(cat "$temp_file")" 2>/dev/null || echo "")
if [[ -n "$claude_sanitized" ]]; then
# Use Claude's sanitized version
sanitized_log="$claude_sanitized"
success "Claude Code: Additional sensitive data removed"
# Optional: Show what Claude changed
if [[ "$VERBOSE" == "true" ]]; then
info "Claude Code sanitization applied"
fi
else
warning "Claude Code sanitization failed, using basic sanitization only"
fi
rm -f "$temp_file"
fi
# Prepare issue title and body
local issue_title
issue_title="[Automated] Playbook failure: $(basename "$playbook_name") on Fedora $fedora_version"
local issue_body
issue_body="## Playbook Failure Report
### Environment
- **Fedora Version**: $fedora_version
- **Branch**: $branch
- **Commit**: $commit
- **Hostname**: $hostname
- **Kernel**: $kernel
- **Date**: $(date -u +"%Y-%m-%d %H:%M:%S UTC")
### Failed Playbook
\`\`\`
$playbook_name
\`\`\`
### Exit Code
$exit_code
### Error Output
<details>
<summary>Click to expand error log</summary>
\`\`\`
$sanitized_log
\`\`\`
</details>
### Steps to Reproduce
1. Fresh Fedora $fedora_version installation
2. Run \`./run.bash\`
3. Playbook fails at: $playbook_name
### Additional Context
_This issue was automatically generated. The error log has been sanitized to remove potentially sensitive information._
---
_Generated by fedora-desktop automated error reporting_"
# Show preview to user
echo -e "\n${CYAN}${BOLD}Issue Preview${NC}"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BOLD}Title:${NC} $issue_title\n"
echo -e "${BOLD}Body:${NC}"
echo "$issue_body" | head -n 50
echo -e "\n... [truncated for preview] ...\n"
# Ask for confirmation
if confirm "Do you want to create this GitHub issue?"; then
info "Creating GitHub issue..."
# Create the issue
local issue_url
if issue_url=$(${GH_REPO:-gh} issue create \
--title "$issue_title" \
--body "$issue_body" \
--label "bug" \
--label "automated" \
2>&1); then
success "Issue created successfully!"
echo -e "${GREEN}${ARROW} View issue: $issue_url${NC}"
return 0
else
error "Failed to create issue: $issue_url"
return 1
fi
else
info "Issue creation cancelled"
return 1
fi
}
# Function to run playbook with option to create issue on failure
run_playbook_with_issue_option(){
local playbook="$1"
local name="$2"
local exit_code=0
echo -e "\n${CYAN}${ARROW} Running: $name${NC}"
# Run playbook normally with full colors
if sudo -n true 2>/dev/null; then
"$playbook"
exit_code=$?
else
"$playbook" --ask-become-pass
exit_code=$?
fi
if [[ $exit_code -eq 0 ]]; then
success "Completed: $name"
return 0
else
error "Failed: $name (exit code: $exit_code)"
# Offer to create GitHub issue
if confirm "Would you like to create a GitHub issue for this failure?"; then
create_github_issue "$playbook" "$exit_code"
fi
return $exit_code
fi
}
promptForValue(){
local item v yn validate
item="$1"
validate="${2:-}"
while true; do
echo -e "\n${CYAN}${ARROW}${NC} Please enter your ${BOLD}$item${NC}:" 1>&2
read -rp " " v
# Basic validation: must not be empty
if [[ -z "${v// /}" ]]; then
echo -e " ${RED}${CROSS} Cannot be empty${NC}" 1>&2
continue
fi
# Custom validation
if [[ "$validate" == "email" ]] && [[ "$v" != *@*.* ]]; then
echo -e " ${RED}${CROSS} Must be a valid email address${NC}" 1>&2
continue
fi
if [[ "$validate" == "min3" ]] && [[ "${#v}" -lt 3 ]]; then
echo -e " ${RED}${CROSS} Must be at least 3 characters${NC}" 1>&2
continue
fi
echo -e "\n You entered: ${BOLD}$v${NC}" 1>&2
read -rsp " Is this correct? (y/n): " -n 1 yn 1>&2
echo 1>&2
[[ "$yn" == "y" ]] && break
done
echo "$v"
}
## Process
if [[ "$OPTIONAL_ONLY" != "true" ]]; then
echo -e "\n${MAGENTA}${BOLD}Installation Process${NC}"
echo -e "${MAGENTA}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
wait_for_network
echo -e "\n${YELLOW}${INFO} You will be asked for your sudo password${NC}\n"
title "Installing System Dependencies"
info "Installing: git, python3, python3-libdnf5, grubby, jq, openssl, pipx"
sudo dnf -y install \
git \
python3 \
python3-pip \
python3-libdnf5 \
grubby \
jq \
openssl \
pipx > /dev/null 2>&1
completed
title "Checking for Legacy Grub Configurations"
info "Checking for old cgroup settings"
if sudo grubby --info=ALL 2>/dev/null | grep -q "systemd.unified_cgroup_hierarchy"; then
warning "Found legacy cgroup configuration, removing..."
sudo grubby --update-kernel=ALL --remove-args="systemd.unified_cgroup_hierarchy=0"
sudo grubby --update-kernel=ALL --remove-args="systemd.unified_cgroup_hierarchy=1"
# Verify the removal worked
if sudo grubby --info=ALL 2>/dev/null | grep -q "systemd.unified_cgroup_hierarchy"; then
error "Failed to remove cgroup configuration - may need manual intervention"
echo -e "${YELLOW}${INFO} To manually remove, run:${NC}"
echo -e " sudo grubby --update-kernel=ALL --remove-args='systemd.unified_cgroup_hierarchy=0'"
else
success "Legacy cgroup configuration removed successfully"
fi
else
success "No legacy cgroup configuration found"
fi
title "Setting up Ansible Environment"
# sudo dnf install pipx (above) or the kickstart %post can create ~/.local owned
# by root, which causes pipx to fail with PermissionError on its log directory.
# Fix ownership before running pipx.
if [[ -d ~/.local ]] && [[ "$(stat -c%U ~/.local)" != "$(whoami)" ]]; then
info "Fixing ~/.local ownership (was created by root)"
sudo chown -R "$(id -u):$(id -g)" ~/.local
fi
mkdir -p ~/.local/bin ~/.local/share ~/.local/state
info "Installing Ansible and dependencies via pipx"
if pipx list --short | grep -q "ansible"; then
success "Ansible already installed"
else
pipx install --include-deps ansible
pipx inject ansible jmespath
pipx inject ansible passlib
pipx inject ansible ansible-lint
fi
# Ensure ~/.local/bin exists, then force-create symlink
mkdir -p ~/.local/bin
ln -sf ~/.local/share/pipx/venvs/ansible/bin/ansible-lint ~/.local/bin/ansible-lint
completed
_ssh_key_password="" # saved here, offered as default for github_ SSH keys later
title "Creating SSH Key Pair\n\nNOTE - you must set a password\n\nSuggest you use your login password"
if [[ ! -f ~/.ssh/id ]]; then
while true; do
read -rsp "Password: " password
echo
read -rsp "Password (confirm): " password2
echo
[ "$password" = "$password2" ] && break
echo "Passwords not matched, please try again"
done
ssh-keygen -t ed25519 -f ~/.ssh/id -P "$password"
_ssh_key_password="$password"
else
echo " - found existing key"
fi
completed
title "Set Custom Hostname"
if [[ "$(hostname)" == "fedora" ]]; then
echo "found default hostname, please choose a new one"
echo "(your machine hostname, eg joseph-laptop, joseph-fedora etc)"
read -rp "Hostname: " hostname
sudo hostnamectl set-hostname "$hostname"
fi
title "Installing Github CLI"
sudo dnf -y install 'dnf-command(config-manager)'
# Check if gh-cli repo already exists before adding
if ! sudo dnf repolist | grep -q "gh-cli"; then
sudo dnf config-manager addrepo --from-repofile=https://cli.github.com/packages/rpm/gh-cli.repo
else
echo "GitHub CLI repository already configured"
fi
sudo dnf -y install gh
completed
title "GitHub Authentication Setup"
info "You will need to authenticate with your browser"
# Only add GH_HOST if not already present
if ! grep -q 'export GH_HOST="github.com"' ~/.bashrc; then
echo 'export GH_HOST="github.com"' >> ~/.bashrc
fi
# When setting up the github token, some required permissions might be missed out
# This function allows us to check for the required permissions
function ghCheckTokenPermission(){
local permission="$1"
local failSilent="${2:-false}"
local gh_cmd="${GH_REPO:-gh}"
local scopes
scopes="$($gh_cmd api -i user | grep 'X-Oauth-Scopes')"
if [[ "$scopes" == *"$permission"* ]]; then
echo " - found $permission permission"
return 0
else
if [[ "$failSilent" == "true" ]]; then
return 1
fi
echo " - missing $permission permission"
echo "Please run this command ON THE MACHINE ITSELF, NOT REMOTELY
$gh_cmd auth refresh -h github.com -s '$permission'
"
return 1
fi
}
if ! gh auth status > /dev/null 2>&1; then
echo -e "\n${YELLOW}${BOLD}┌─────────────────────────────────────────────────┐${NC}"
echo -e "${YELLOW}${BOLD}│ IMPORTANT │${NC}"
echo -e "${YELLOW}${BOLD}│ YOU MUST CHOOSE SSH WHEN ASKED FOR THE │${NC}"
echo -e "${YELLOW}${BOLD}│ PREFERRED PROTOCOL FOR GIT OPERATIONS │${NC}"
echo -e "${YELLOW}${BOLD}└─────────────────────────────────────────────────┘${NC}\n"
read -rp "Confirm you will choose SSH for GitHub authentication (Y/n): " confirm_ssh
if [[ "${confirm_ssh,,}" == "n" ]]; then
error "SSH is required - please re-run and choose SSH"
exit 1
fi
if ! gh auth login; then
error "Failed to login to GitHub"
echo -e "${YELLOW}${ARROW} Please try running 'gh auth login' manually${NC}"
exit 1
fi
success "GitHub authentication successful"
else
success "Already authenticated with GitHub"
fi
primary_gh_username="$(gh api user --jq '.login')"
success "Primary GitHub account: $primary_gh_username"
completed
# This repo lives in the LongTermSupport org. If a previous install set up
# multi-account wrappers (play-github-cli-multi.yml generates gh-<alias> bash
# functions), prefer gh-lts for operations that act on this repo — so we talk
# to GitHub as the LTS account even when a different account is the active
# default. Falls back to plain gh on fresh installs where the wrappers don't
# yet exist.
GH_REPO="gh"
_gh_aliases_file="$HOME/.bashrc-includes/gh-aliases.inc.bash"
if [[ -f "$_gh_aliases_file" ]]; then
# shellcheck source=/dev/null
source "$_gh_aliases_file"
if declare -F gh-lts >/dev/null; then
GH_REPO="gh-lts"
info "Using gh-lts wrapper for LTS-org operations"
fi
fi
export GH_REPO
title "Configuring GitHub SSH Access"
# Check if we have the required permission
if ! ghCheckTokenPermission "admin:public_key" > /dev/null 2>&1; then
warning "Missing admin:public_key permission - requesting it now"
$GH_REPO auth refresh -h github.com -s admin:public_key
fi
ssh_key_fingerprint=$(ssh-keygen -lf ~/.ssh/id.pub | awk '{print $2}')
# Use gh api to check for SSH keys without triggering signing key scope warning
if ! $GH_REPO api user/keys 2>/dev/null | grep -q "$ssh_key_fingerprint"; then
# Add SSH key for authentication only (not signing)
if $GH_REPO ssh-key add ~/.ssh/id.pub --title="$(hostname) Added by fedora-desktop setup script on $(date +%Y-%m-%d)" --type=authentication 2>&1; then
success "SSH authentication key added to GitHub"
else
error "Failed to add SSH key to GitHub"
echo -e "${YELLOW}${ARROW} Try manually adding your SSH key:${NC}"
echo -e " cat ~/.ssh/id.pub | $GH_REPO ssh-key add --title='$(hostname)' --type=authentication"
exit 1
fi
else
success "SSH key already configured on GitHub"
fi
completed
title "Updating SSH Known Hosts"
info "Configuring GitHub host keys"
# Remove existing GitHub entries silently
ssh-keygen -R github.com &>/dev/null || true
# Add fresh GitHub host keys
curl -sL https://api.github.com/meta | jq -r '.ssh_keys | .[]' | sed -e 's/^/github.com /' >> ~/.ssh/known_hosts
success "GitHub host keys updated"
completed
title "Setting up Project Directory and Repository"
mkdir -p ~/Projects
if [[ ! -d ~/Projects/fedora-desktop ]]; then
info "Cloning fedora-desktop repository"
git clone https://github.com/LongTermSupport/fedora-desktop.git ~/Projects/fedora-desktop
success "Repository cloned"
else
info "Pulling latest changes"
assert_clean_worktree ~/Projects/fedora-desktop
# Use `command git` to bypass any git() bash wrapper function (e.g. from
# gh-aliases.inc.bash). Wrappers that run subcommands and assign to vars
# can propagate non-zero exits under `set -e` even when they're benign.
command git -C ~/Projects/fedora-desktop pull
success "Repository updated"
fi
cd ~/Projects/fedora-desktop
# Fail fast: verify Fedora version matches this branch
version_file=~/Projects/fedora-desktop/vars/fedora-version.yml
if [[ ! -f "$version_file" ]]; then
error "Cannot find $version_file — repository may be corrupt"
exit 1
fi
expected_version=$(grep "fedora_version:" "$version_file" | cut -d: -f2 | tr -d ' ')
if [[ "$fedora_version" != "$expected_version" ]]; then
error "Fedora version mismatch"
echo -e " Expected: Fedora ${BOLD}$expected_version${NC} (from branch)"
echo -e " Actual: Fedora ${BOLD}$fedora_version${NC}"
echo -e "\n${YELLOW}${ARROW} Check out the correct branch for your Fedora version${NC}"
exit 1
fi
success "Fedora version verified: $fedora_version matches branch"
completed
title "Loading Personal Configuration"
localhost_yml=~/Projects/fedora-desktop/environment/localhost/host_vars/localhost.yml
config_repo="${primary_gh_username}/fedora-desktop-config"
# Check if config repo exists
has_config_repo=false
if raw_content=$(gh api "repos/${config_repo}/contents/localhost.yml" --jq '.content' 2>/dev/null); then
has_config_repo=true
info "Config repo found: github.com/${config_repo}"
else
info "No config repo found at github.com/${config_repo}"
fi
# Present configuration source choice
echo -e "\n${CYAN}${ARROW}${NC} How would you like to configure this system?"
_option=1
if [[ "$has_config_repo" == "true" ]]; then
echo -e " ${_option}) Pull saved configuration from config repo (recommended)"
_opt_pull=$_option
(( _option++ ))
fi
if [[ -f "$localhost_yml" ]] && grep -qE '(!vault|github_accounts)' "$localhost_yml"; then
echo -e " ${_option}) Keep existing local configuration"
_opt_keep=$_option
(( _option++ ))
fi
echo -e " ${_option}) Configure fresh (enter details manually)"
_opt_fresh=$_option
read -rp " Choice [1-${_option}]: " _config_choice
if [[ "$has_config_repo" == "true" ]] && [[ "${_config_choice}" == "${_opt_pull}" ]]; then
printf '%s' "$raw_content" | base64 -d > "$localhost_yml"
success "Configuration pulled from github.com/${config_repo}"
elif [[ -n "${_opt_keep:-}" ]] && [[ "${_config_choice}" == "${_opt_keep}" ]]; then
success "Keeping existing localhost.yml"
elif [[ "${_config_choice}" == "${_opt_fresh}" ]]; then
echo ""
read -rp " User login [$(whoami)]: " user_login
user_login="${user_login:-$(whoami)}"
if [[ ${#user_login} -lt 3 ]]; then
error "User login must be at least 3 characters"
exit 1
fi
read -rp " Full name [${user_login}]: " user_name
user_name="${user_name:-$user_login}"
user_email="$(promptForValue 'email address' email)"
echo -e "\n${CYAN}${ARROW}${NC} Enter your GitHub username(s)"
echo -e " These are the usernames you log into github.com with."
echo -e " For multiple accounts, prefix each with a short alias and colon."
echo -e ""
echo -e " ${BOLD}One account:${NC} johndoe"
echo -e " ${BOLD}Multiple accounts:${NC} personal:johndoe,work:johndoe-corp"
github_accounts_raw="$(promptForValue 'GitHub username(s), comma separated')"
# Count entries and validate format
_account_count=$(printf '%s' "$github_accounts_raw" | tr ',' '\n' | grep -c '[^[:space:]]')
_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"
echo -e " You entered: ${BOLD}${github_accounts_raw}${NC}"
echo -e " Example: ${BOLD}personal:user1,work:user2${NC}"
exit 1
fi
# Validate: no duplicate aliases
declare -A _seen_aliases=()
while IFS= read -r pair; do
pair="${pair// /}"
if [[ "$pair" == *":"* ]]; then
_alias="${pair%%:*}"
elif [[ -n "$pair" ]]; then
_alias="personal"
else
continue
fi
if [[ -n "${_seen_aliases[$_alias]:-}" ]]; then
error "Duplicate alias '${_alias}' — each account needs a unique alias"
exit 1
fi
_seen_aliases[$_alias]=1
done < <(printf '%s\n' "$github_accounts_raw" | tr ',' '\n')
{
printf 'user_login: "%s"\n' "$user_login"
printf 'user_name: "%s"\n' "$user_name"
printf 'user_email: "%s"\n' "$user_email"
printf '# GitHub CLI accounts\n'
printf 'github_accounts:\n'
while IFS= read -r pair; do
pair="${pair// /}"
if [[ "$pair" == *":"* ]]; then
printf ' %s: "%s"\n' "${pair%%:*}" "${pair##*:}"
elif [[ -n "$pair" ]]; then
printf ' personal: "%s"\n' "$pair"
fi
done < <(printf '%s\n' "$github_accounts_raw" | tr ',' '\n')
} > "$localhost_yml"
success "Configuration written"
else
error "Invalid choice: ${_config_choice}"
exit 1
fi
completed
title "Ansible Vault Configuration"
vault_pass_file=~/Projects/fedora-desktop/vault-pass.secret
if grep -qF '!vault' "$localhost_yml" 2>/dev/null; then
# localhost.yml has encrypted values — need the matching vault password
if [[ -f "$vault_pass_file" ]] && [[ -s "$vault_pass_file" ]]; then
# Test existing vault password against encrypted values
if ansible localhost -c local -e "@$localhost_yml" -m debug -a "msg=vault_ok" \
--vault-id "localhost@$vault_pass_file" 2>/dev/null | grep -q "vault_ok"; then
success "Existing vault password verified"
else
error "Existing vault-pass.secret cannot decrypt localhost.yml"
echo -e " ${YELLOW}${ARROW}${NC} The file exists but the password is wrong."
echo -e " Enter the correct vault password (from your password manager):"
read -rsp " " vaultPass
echo
echo "$vaultPass" > "$vault_pass_file"
chmod 600 "$vault_pass_file"
success "Vault password updated"
fi
else
echo -e "\n${CYAN}${ARROW}${NC} Your localhost.yml has vault-encrypted values."
echo -e " Enter your vault password (from your password manager):"
read -rsp " " vaultPass
echo
echo "$vaultPass" > "$vault_pass_file"
chmod 600 "$vault_pass_file"
success "Vault password configured"
fi
elif [[ -f "$vault_pass_file" ]]; then
success "Existing vault password found"
else
info "Setting up Ansible vault"
echo -e "\n${CYAN}${ARROW}${NC} Enter vault password (or leave blank to auto-generate):"
read -rsp " " vaultPass
echo
if [[ "" == "$vaultPass" ]]; then
vaultPass="$(openssl rand -base64 32)"
success "Generated new vault password"
else
success "Vault password configured"
fi
echo "$vaultPass" > "$vault_pass_file"
fi
completed
title "GitHub SSH Key Passphrase"
# GitHub SSH keys (github_*) are full account keys — they must be passphrase-protected.
# The passphrase is stored in the vault so the Ansible playbook can manage keys idempotently.
_github_ssh_passphrase=""
if grep -q 'github_ssh_passphrase:' "$localhost_yml" 2>/dev/null; then
success "github_ssh_passphrase already configured in localhost.yml"
else
info "GitHub SSH keys require a passphrase (these are full account keys, not deploy keys)"
echo
if [[ -n "$_ssh_key_password" ]]; then
echo -e "${CYAN}${ARROW}${NC} Use the same password as your main SSH key (~/.ssh/id) for all GitHub keys?"
read -rsp " Press 'y' to use same, 'n' to enter a different one: " -n 1 _yn
echo
if [[ "${_yn,,}" == "y" ]]; then
_github_ssh_passphrase="$_ssh_key_password"
success "Using same password as ~/.ssh/id"
fi
fi
if [[ -z "$_github_ssh_passphrase" ]]; then
info "Hint: your login password is a convenient choice"
while true; do
read -rsp " GitHub SSH keys passphrase: " _github_ssh_passphrase
echo
read -rsp " Confirm passphrase: " _confirm_passphrase
echo
[[ "$_github_ssh_passphrase" == "$_confirm_passphrase" ]] && break
echo -e "${RED}${CROSS} Passphrases do not match — try again${NC}"
done
fi
info "Encrypting github_ssh_passphrase and saving to vault..."
# printf avoids trailing newline that echo adds — passphrase must be exact
_encrypted=$(printf '%s' "$_github_ssh_passphrase" | ansible-vault encrypt_string \
--stdin-name 'github_ssh_passphrase')
printf '\n%s\n' "$_encrypted" >> "$localhost_yml"
success "github_ssh_passphrase saved to localhost.yml (vault-encrypted)"
fi
completed
title "Preparing SSH Keys for GitHub Accounts"
if grep -q 'github_accounts' "$localhost_yml" 2>/dev/null; then
info "Generating any missing per-account SSH keys"
# Parse github_accounts from localhost.yml — use Python to ignore !vault tags
mapfile -t _gh_account_pairs < <(python3 - "$localhost_yml" <<'PYEOF'
import sys, yaml
def _ignore_vault(loader, tag_suffix, node):
return None
_loader = yaml.SafeLoader
yaml.add_multi_constructor('', _ignore_vault, Loader=_loader)
with open(sys.argv[1]) as f:
data = yaml.load(f, Loader=_loader)
for alias, username in (data.get('github_accounts') or {}).items():
print(f"{alias}:{username}")
PYEOF
)
if [[ ${#_gh_account_pairs[@]} -eq 0 ]]; then
warning "No github_accounts entries parsed — skipping"
else
# If any key needs generating and passphrase isn't in memory (e.g. pulled from config
# repo), prompt once before the loop rather than letting ssh-keygen use empty passphrase
_any_key_missing=false
for _pair in "${_gh_account_pairs[@]}"; do
_alias="${_pair%%:*}"
[[ ! -f "$HOME/.ssh/github_${_alias}" ]] && { _any_key_missing=true; break; }
done
if [[ "$_any_key_missing" == "true" ]] && [[ -z "$_github_ssh_passphrase" ]]; then
# Passphrase exists in vault (from config repo) — decrypt it rather than
# asking the user to re-type it, which risks a mismatch
info "Decrypting github_ssh_passphrase from vault..."
# Force minimal callback to get predictable JSON output regardless of ansible.cfg
_github_ssh_passphrase=$(ANSIBLE_STDOUT_CALLBACK=ansible.builtin.minimal \
ansible localhost -c local \
-e "@$localhost_yml" \
-m debug -a "msg={{ github_ssh_passphrase }}" \
--vault-id "localhost@$vault_pass_file" 2>/dev/null \
| python3 -c "import sys,json,re;raw=sys.stdin.read();m=re.search(r'=>\s*(\{.*\})',raw,re.DOTALL);print(json.loads(m.group(1))['msg'],end='')" 2>/dev/null)
if [[ -z "$_github_ssh_passphrase" ]]; then
error "Failed to decrypt github_ssh_passphrase from vault"
echo -e " ${YELLOW}${ARROW}${NC} Check that vault-pass.secret is correct"
exit 1
fi
success "Passphrase decrypted from vault"
fi
for _pair in "${_gh_account_pairs[@]}"; do
_alias="${_pair%%:*}"
_username="${_pair##*:}"
# Ensure per-account SSH key exists — playbook will handle GitHub upload
_key_private="$HOME/.ssh/github_${_alias}"
if [[ ! -f "$_key_private" ]]; then
info "Generating SSH key for $_alias ($_username)"
ssh-keygen -t ed25519 -C "${_username}@github" -f "$_key_private" -N "${_github_ssh_passphrase:-}"
fi
success "SSH key ready: $_alias ($_username)"
done
fi
else
success "Single account setup — no additional accounts to authenticate"
fi
completed
title "Running Ansible Playbooks"
info "Pulling latest changes before running playbooks"
assert_clean_worktree ~/Projects/fedora-desktop
# See note above on `command git` — bypass any sourced git() wrapper.
command git pull
success "Repository up to date"
info "Installing Ansible requirements"
ansible-galaxy install -r requirements.yml > /dev/null 2>&1
success "Requirements installed"
info "Executing main configuration playbook"
echo -e "${YELLOW}${INFO} This may take several minutes...${NC}\n"
# Run main playbook normally with full colors
main_exit_code=0
if sudo -n true 2>/dev/null; then
./playbooks/playbook-main.yml
main_exit_code=$?
else
echo -e "${YELLOW}${INFO} You will be prompted for your sudo password${NC}"
./playbooks/playbook-main.yml --ask-become-pass
main_exit_code=$?
fi
if [[ $main_exit_code -eq 0 ]]; then
completed
else
error "Main playbook failed with exit code: $main_exit_code"
# Offer to create GitHub issue
if confirm "Would you like to create a GitHub issue for this failure?"; then
create_github_issue "./playbooks/playbook-main.yml" "$main_exit_code"
fi
# Ask if user wants to continue despite failure
if ! confirm "Do you want to continue with optional playbooks despite the main playbook failure?"; then
error "Installation aborted due to main playbook failure"
exit $main_exit_code
fi
fi
## ── Restore Projects ─────────────────────────────────────────────────────────
title "Restoring Projects"
_pull_projects_script=~/Projects/fedora-desktop/fedora-install/pull-projects.bash
if [[ -f "$_pull_projects_script" ]]; then
if confirm "Would you like to restore projects from your config repo manifest?"; then
if ! "$_pull_projects_script" --account "$primary_gh_username"; then
warning "Projects restore failed or no manifest found — continuing"
fi
fi
else
warning "pull-projects.bash not found — skipping project restore"
fi
echo -e "\n${GREEN}${BOLD}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}${BOLD}║ MAIN INSTALLATION COMPLETE! ║${NC}"
echo -e "${GREEN}${BOLD}╚══════════════════════════════════════════════════════════════╝${NC}\n"
fi # end: OPTIONAL_ONLY skip block
## Optional Playbooks Menu System
# Function to run a playbook (wrapper for backward compatibility)
run_playbook() {
run_playbook_with_issue_option "$1" "$2"
}
# Parse a space/comma-separated list of numbers; print valid ones (one per line)
_parse_number_list() {
local input="$1"
local max="$2"
local -a tokens
# Global IFS=$'\n\t' excludes spaces, so use explicit IFS for splitting
IFS=' ,' read -ra tokens <<< "$input"
for n in "${tokens[@]}"; do
[[ -z "$n" ]] && continue
if [[ "$n" =~ ^[0-9]+$ ]] && [[ "$n" -ge 1 ]] && [[ "$n" -le "$max" ]]; then
echo "$n"
else
warning "Ignoring invalid number: $n (valid range: 1-$max)" >&2
fi
done
}
# Function to display menu
show_menu() {
local category="$1"
shift
local playbooks=("$@")
local choice
while true; do
echo -e "\n${CYAN}${BOLD}$category Playbooks${NC}"