-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall-github-cli.sh
More file actions
1879 lines (1566 loc) · 57.9 KB
/
install-github-cli.sh
File metadata and controls
1879 lines (1566 loc) · 57.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# SPDX-License-Identifier: NCSA
#===============================================================================
# install-github-cli.sh - GitHub CLI installer with Git/SSH configuration
#
# DESCRIPTION:
# Script to install GitHub CLI and configure Git authentication.
# Supports browser-based OAuth, SSH key generation, and Git identity setup.
# Non-interactive (where possible) and idempotent.
#
# REQUIREMENTS:
# Bash 5.2+
# Debian 13 Trixie in WSL2
#
# USAGE:
# sudo ./install-github-cli.sh --user USERNAME
# sudo ./install-github-cli.sh --user USERNAME --verbose
# sudo ./install-github-cli.sh --user USERNAME --skip-ssh
# sudo ./install-github-cli.sh --remove
# sudo ./install-github-cli.sh --remove --purge --force
#
# INSTALLATION OPTIONS:
# --user USERNAME Target user for authentication (required)
# --skip-ssh Skip SSH key generation and upload
# --skip-git-config Skip Git identity configuration
# --ssh-key-comment Custom comment for SSH key
#
# REMOVAL OPTIONS:
# --remove Remove GitHub CLI and repository configuration
# --purge Also remove SSH keys created by this script
# --force, -f Skip confirmation prompts
#
# GENERAL OPTIONS:
# --dry-run Show what would be done without making changes
# --verbose, -v Enable verbose output
# --syslog Also log to syslog (for enterprise environments)
# --help, -h Show this help message
#
# ENVIRONMENT:
# TRACE=1 Enable bash debug tracing
#
# LICENSE: NCSA
#===============================================================================
# shellcheck enable=check-set-e-suppressed
# shellcheck enable=check-extra-masked-returns
#-------------------------------------------------------------------------------
# Bash Version Check
#-------------------------------------------------------------------------------
if ((BASH_VERSINFO[0] < 5 || (BASH_VERSINFO[0] == 5 && BASH_VERSINFO[1] < 2))); then
printf 'Error: This script requires Bash 5.2+. Current: %s\n' "${BASH_VERSION}" >&2
exit 1
fi
#-------------------------------------------------------------------------------
# Strict Mode & Safety Settings
#-------------------------------------------------------------------------------
set -o errexit
set -o errtrace
set -o nounset
set -o pipefail
shopt -s extglob
shopt -s globskipdots
shopt -s inherit_errexit
shopt -s assoc_expand_once
# Enable debug tracing if TRACE=1
[[ ${TRACE:-0} == 1 ]] && set -o xtrace
#-------------------------------------------------------------------------------
# Constants
#-------------------------------------------------------------------------------
declare -r SCRIPT_NAME="${0##*/}"
declare -r SCRIPT_VERSION="1.0.0"
declare -r LOG_FILE="/var/log/github-cli-install.log"
declare -r LOCK_FILE="/var/lock/github-cli-install.lock"
# GitHub CLI repository configuration
declare -r GH_GPG_URL="https://cli.github.com/packages/githubcli-archive-keyring.gpg"
declare -r GH_REPO_URL="https://cli.github.com/packages"
# GitHub CLI GPG key fingerprint for verification
# Renewed September 2024, expires September 2026
# Source: https://github.blog/changelog/2024-09-11-github-cli-renews-gpg-signing-key-for-linux-packages/
declare -r GH_GPG_FINGERPRINT="2C6106201985B60E6C7AC87323F3D4EA75716059"
# Allowed domains for downloads (security allowlist)
declare -ra ALLOWED_DOWNLOAD_DOMAINS=(cli.github.com github.com api.github.com)
# Network retry configuration
declare -ri MAX_RETRIES=5
declare -ri RETRY_DELAY_BASE=2
# Lock timeout (seconds) - prevents deadlocks from stuck processes
declare -ri LOCK_TIMEOUT=300
# shellcheck disable=SC2034 # EXIT_SUCCESS defined for completeness/documentation
declare -ri EXIT_SUCCESS=0
declare -ri EXIT_GENERAL_ERROR=1
declare -ri EXIT_LOCK_FAILED=2
declare -ri EXIT_INVALID_ARGS=3
declare -ri EXIT_ROOT_REQUIRED=4
declare -ri EXIT_NOT_WSL2=5
declare -ri EXIT_UNSUPPORTED_DISTRO=6
declare -ri EXIT_NETWORK_ERROR=7
declare -ri EXIT_INSTALL_FAILED=8
declare -ri EXIT_AUTH_FAILED=9
declare -ri EXIT_SSH_FAILED=10
# shellcheck disable=SC2034 # EXIT_USER_CANCELLED defined for completeness/documentation
declare -ri EXIT_USER_CANCELLED=11
declare -ra REQUIRED_COMMANDS=(
curl apt-get dpkg-query getent id stat mkdir rm mv cp chmod
gpg awk grep sed tee sleep flock pgrep uname sha256sum cut mktemp
ssh-keygen
)
# Files/directories managed by this installer
declare -r GH_GPG_KEY="/etc/apt/keyrings/githubcli-archive-keyring.gpg"
declare -r GH_SOURCES_FILE="/etc/apt/sources.list.d/github-cli.sources"
declare -r SSH_CONFIG_MARKER="# GitHub SSH config (managed by install-github-cli.sh)"
#-------------------------------------------------------------------------------
# Global State Variables
#-------------------------------------------------------------------------------
declare TARGET_USER="${SUDO_USER:-}"
declare DRY_RUN=false
declare VERBOSE=false
declare SYSLOG=false
declare SKIP_SSH=false
declare SKIP_GIT_CONFIG=false
declare SSH_KEY_COMMENT=""
# Removal mode state
declare REMOVE_MODE=false
declare PURGE_DATA=false
declare FORCE_REMOVE=false
declare ARCH=""
# Cleanup state tracking (for rollback)
declare -i CLEANUP_IN_PROGRESS=0
declare -i SIGNAL_RECEIVED=0
declare RECEIVED_SIGNAL=""
declare -a CLEANUP_ACTIONS=()
declare -A CREATED_FILES=()
declare -A MODIFIED_FILES=()
#-------------------------------------------------------------------------------
# Terminal Colours
#-------------------------------------------------------------------------------
declare -A COLORS
if [[ -t 1 && ${TERM:-dumb} != dumb ]]; then
COLORS=(
[red]='\033[0;31m'
[green]='\033[0;32m'
[yellow]='\033[0;33m'
[blue]='\033[0;34m'
[cyan]='\033[0;36m'
[bold]='\033[1m'
[reset]='\033[0m'
)
else
COLORS=([red]='' [green]='' [yellow]='' [blue]='' [cyan]='' [bold]='' [reset]='')
fi
#-------------------------------------------------------------------------------
# Logging
#-------------------------------------------------------------------------------
_log() {
local -r level="$1" color="$2" msg="$3"
local timestamp
printf -v timestamp '%(%Y-%m-%d %H:%M:%S)T' "${EPOCHSECONDS}"
printf '%b[%s]%b %s - %s\n' "${COLORS[${color}]}" "${level}" "${COLORS[reset]}" "${timestamp}" "${msg}" | tee -a "${LOG_FILE}"
_syslog "${level}" "${msg}"
}
log_info() { _log "INFO " "blue" "$1"; }
log_success() { _log "OK " "green" "$1"; }
log_warn() { _log "WARN " "yellow" "$1" >&2; }
log_error() { _log "ERROR" "red" "$1" >&2; }
log_debug() {
if [[ ${VERBOSE} == true ]]; then
_log "DEBUG" "cyan" "$1"
fi
}
# Send to syslog if enabled
_syslog() {
local -r level="$1" msg="$2"
local has_logger=false
# shellcheck disable=SC2310 # Intentional: capture result in variable
has_command logger && has_logger=true
if [[ ${SYSLOG} == true && ${has_logger} == true ]]; then
logger -t "${SCRIPT_NAME}" -p "user.${level,,}" "${msg}" 2>/dev/null || true
fi
}
log_step() {
local -r step="$1" desc="$2"
printf '\n%b%b[Step %s]%b %s\n' "${COLORS[bold]}" "${COLORS[blue]}" "${step}" "${COLORS[reset]}" "${desc}" | tee -a "${LOG_FILE}"
printf '%s\n' "$(printf -- '-%.0s' {1..60})" | tee -a "${LOG_FILE}"
}
#-------------------------------------------------------------------------------
# Utility Functions
#-------------------------------------------------------------------------------
die() {
log_error "$1"
exit "${2:-1}"
}
# Prompt for confirmation
# Returns: 0 if confirmed, 1 if declined
confirm_action() {
local -r prompt="${1}"
# Force mode bypasses confirmation
[[ ${FORCE_REMOVE} == true ]] && return 0
# Dry-run mode assumes yes for preview
if [[ ${DRY_RUN} == true ]]; then
log_info "[DRY-RUN] Would prompt: ${prompt}"
return 0
fi
# Non-interactive mode: use safe default (decline)
if [[ ! -t 0 ]]; then
log_warn "Non-interactive mode - use --force to proceed"
return 1
fi
# Interactive prompt
printf '%b%s [y/N]: %b' "${COLORS[yellow]}" "${prompt}" "${COLORS[reset]}"
local response
read -r response
[[ ${response,,} =~ ^(y|yes)$ ]]
}
# Retry with exponential backoff
retry_with_backoff() {
local -ri max_attempts="$1"
local -i delay="$2"
shift 2
local -a cmd=("$@")
local -i attempt=1
local output
local -i exit_code
while ((attempt <= max_attempts)); do
if output=$("${cmd[@]}" 2>&1); then
return 0
fi
exit_code=$?
if ((attempt == max_attempts)); then
log_error "Command failed after ${max_attempts} attempts: ${cmd[*]@Q}"
log_error "Last output: ${output}"
return 1
fi
# Check for rate limiting or server errors
if [[ ${output} =~ (429|503|"Too Many Requests"|"Service Unavailable") ]]; then
log_warn "Server rate-limited or unavailable (attempt ${attempt}/${max_attempts})"
((delay *= 3))
else
log_warn "Attempt ${attempt}/${max_attempts} failed (exit code: ${exit_code}). Retrying in ${delay}s..."
((delay *= 2))
fi
# Cap maximum delay
((delay > 60)) && delay=60
sleep "${delay}"
((attempt++))
done
}
has_command() {
command -v "$1" &>/dev/null
}
# Validate URL format and domain allowlist
validate_url() {
local -r url="$1"
local -r pattern='^https://[a-zA-Z0-9][-a-zA-Z0-9]*(\.[a-zA-Z0-9][-a-zA-Z0-9]*)+(/[-a-zA-Z0-9_.~%/]*)?$'
# Validate URL format
if [[ ! ${url} =~ ${pattern} ]]; then
die "Invalid URL format: ${url}" "${EXIT_GENERAL_ERROR}"
fi
# Extract domain from URL
local domain
domain="${url#https://}"
domain="${domain%%/*}"
# Validate against allowed domains
local allowed=false
local d
for d in "${ALLOWED_DOWNLOAD_DOMAINS[@]}"; do
if [[ ${domain} == "${d}" ]]; then
allowed=true
break
fi
done
if [[ ${allowed} != true ]]; then
die "URL domain not in allowlist: ${domain}" "${EXIT_GENERAL_ERROR}"
fi
}
# File download with TLS
secure_download() {
local -r url="$1"
local -r output="$2"
local -ri max_size="${3:-10485760}" # 10MB default
# Validate URL before downloading
validate_url "${url}"
curl -fsSL \
--proto '=https' \
--tlsv1.2 \
--connect-timeout 10 \
--max-time 60 \
--retry 3 \
--retry-connrefused \
--max-filesize "${max_size}" \
-o "${output}" \
"${url}"
}
# Check if running in WSL2
is_wsl2() {
local version_info
[[ -f /proc/version ]] || return 1
version_info=$(<"/proc/version")
local -r version_info
[[ ${version_info} =~ [Mm]icrosoft.*[Ww][Ss][Ll]2|[Ww][Ss][Ll]2.*[Mm]icrosoft ]] && return 0
[[ ${version_info} =~ [Mm]icrosoft && -d /run/WSL ]] && return 0
return 1
}
# Execute or simulate based on dry-run mode
execute() {
if [[ ${DRY_RUN} == true ]]; then
log_info "[DRY-RUN] Would execute: ${*@Q}"
return 0
fi
log_debug "Executing: ${*@Q}"
"$@"
}
# APT install with non-interactive settings
apt_install() {
export DEBIAN_FRONTEND=noninteractive
export DEBIAN_PRIORITY=critical
export NEEDRESTART_MODE=a # Auto-restart services without prompting
apt-get install -y -qq \
-o Dpkg::Options::="--force-confdef" \
-o Dpkg::Options::="--force-confold" \
-o Acquire::Retries=3 \
"$@"
}
# Check if package is installed
is_installed() {
dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -q "^install ok installed$"
}
# Verify GPG key fingerprint
verify_gpg_fingerprint() {
local -r keyfile="$1"
local actual_fp
actual_fp=$(gpg --show-keys --with-fingerprint --with-colons "${keyfile}" 2>/dev/null \
| awk -F: '/^fpr:/{gsub(/ /,"",$10); print $10; exit}')
local -r actual_fp
if [[ -z ${actual_fp} ]]; then
die "Failed to extract fingerprint from GPG key" "${EXIT_GENERAL_ERROR}"
fi
if [[ ${actual_fp^^} != "${GH_GPG_FINGERPRINT^^}" ]]; then
log_error "GPG key fingerprint mismatch!"
log_error "Expected: ${GH_GPG_FINGERPRINT}"
log_error "Got: ${actual_fp}"
die "Security verification failed - GPG key may be compromised" "${EXIT_GENERAL_ERROR}"
fi
log_success "GPG key fingerprint verified"
}
# Validate username
validate_username() {
local -r user="$1"
if [[ ! ${user} =~ ^[a-z_][a-z0-9_-]{0,31}$ ]]; then
die "Invalid username format: '${user}'. Must be POSIX-compliant (lowercase, start with letter/underscore, max 32 chars)" "${EXIT_INVALID_ARGS}"
fi
}
validate_required_commands() {
log_info "Validating required commands..."
local -a missing=()
local cmd
for cmd in "${REQUIRED_COMMANDS[@]}"; do
# shellcheck disable=SC2310 # Intentional: capture result in conditional
if ! has_command "${cmd}"; then
missing+=("${cmd}")
fi
done
if ((${#missing[@]} > 0)); then
log_error "Missing required command(s): ${missing[*]}"
die "Install missing commands and try again" "${EXIT_GENERAL_ERROR}"
fi
log_success "All required commands available"
}
#-------------------------------------------------------------------------------
# Locks
#-------------------------------------------------------------------------------
acquire_lock() {
log_debug "Acquiring lock: ${LOCK_FILE}"
mkdir -p "${LOCK_FILE%/*}"
# Open lock file
exec {LOCK_FD}>"${LOCK_FILE}"
if ! flock -w "${LOCK_TIMEOUT}" "${LOCK_FD}"; then
die "Could not acquire lock within ${LOCK_TIMEOUT}s. Another instance may be stuck." "${EXIT_LOCK_FAILED}"
fi
# Write PID for debugging
printf '%d\n' $$ >&"${LOCK_FD}"
log_debug "Lock acquired (PID: $$)"
# Register lock release as cleanup action
register_cleanup "release_lock"
}
release_lock() {
if [[ -v LOCK_FD ]]; then
exec {LOCK_FD}>&- 2>/dev/null || true
log_debug "Lock released"
fi
}
#-------------------------------------------------------------------------------
# Cleanup Action Registry
#-------------------------------------------------------------------------------
register_cleanup() {
local -r action="$1"
CLEANUP_ACTIONS+=("${action}")
log_debug "Registered cleanup action: ${action}"
}
register_created_file() {
local -r file="$1"
CREATED_FILES["${file}"]=1
log_debug "Registered created file: ${file}"
}
register_modified_file() {
local -r file="$1" backup="$2"
MODIFIED_FILES["${file}"]="${backup}"
log_debug "Registered modified file: ${file} (backup: ${backup})"
}
backup_file() {
local -r file="$1"
if [[ -f ${file} ]]; then
local -r backup="${file}.bak.${SRANDOM}"
cp -a "${file}" "${backup}" 2>/dev/null || true
register_modified_file "${file}" "${backup}"
echo "${backup}"
fi
}
atomic_write() {
local -r target="$1"
local -r content="$2"
local temp
temp=$(mktemp "${target}.tmp.XXXXXX") || die "Failed to create temp file for ${target}" "${EXIT_GENERAL_ERROR}"
# Clean up temp file on function exit
trap 'rm -f "${temp}" 2>/dev/null; trap - RETURN' RETURN
# Write to temp file first
printf '%s\n' "${content}" >"${temp}"
mv -f "${temp}" "${target}"
# Clear trap and register for rollback tracking
trap - RETURN
register_created_file "${target}"
}
#-------------------------------------------------------------------------------
# Signal Definitions & Exit Codes
#-------------------------------------------------------------------------------
declare -rA SIGNAL_INFO=(
# Graceful termination signals
[HUP]="1:Hangup:graceful"
[INT]="2:Interrupt:graceful"
[QUIT]="3:Quit:graceful"
[TERM]="15:Terminated:graceful"
# Program error signals
[ILL]="4:Illegal instruction:fatal"
[TRAP]="5:Trace/breakpoint trap:fatal"
[ABRT]="6:Aborted:fatal"
[BUS]="7:Bus error:fatal"
[FPE]="8:Floating point exception:fatal"
[SEGV]="11:Segmentation fault:fatal"
[STKFLT]="16:Stack fault:fatal"
[SYS]="31:Bad system call:fatal"
[IOT]="6:IOT trap:fatal"
)
#-------------------------------------------------------------------------------
# Signal Handler
#-------------------------------------------------------------------------------
signal_handler() {
local -r sig_name="${1:-UNKNOWN}"
local sig_num=1 sig_desc="Unknown signal" sig_type="fatal"
# Prevent re-entrant signal handling
if ((SIGNAL_RECEIVED)); then
return
fi
SIGNAL_RECEIVED=1
RECEIVED_SIGNAL="${sig_name}"
# Parse signal info
if [[ -v SIGNAL_INFO[${sig_name}] ]]; then
IFS=':' read -r sig_num sig_desc sig_type <<<"${SIGNAL_INFO[${sig_name}]}"
fi
local -ri exit_code=$((128 + sig_num))
# Log based on signal type
case "${sig_type}" in
graceful)
log_warn "Received SIG${sig_name} (${sig_desc}) - initiating graceful shutdown..."
;;
fatal)
log_error "FATAL: Received SIG${sig_name} (${sig_desc}) - attempting emergency cleanup..."
log_error "This indicates a serious error. Please report if reproducible."
;;
*)
log_warn "Unknown signal type: ${sig_type}"
;;
esac
# Perform cleanup (will be handled by EXIT trap)
exit "${exit_code}"
}
#-------------------------------------------------------------------------------
# Error Handler
#-------------------------------------------------------------------------------
error_handler() {
local -ri exit_code=$?
local -r failed_cmd="${BASH_COMMAND}"
local -r line="${BASH_LINENO[0]}"
local -r func="${FUNCNAME[1]:-main}"
local -r src="${BASH_SOURCE[1]:-${SCRIPT_NAME}}"
# Don't trigger for intentional failures
((exit_code == 0)) && return 0
log_error "Command failed with exit code ${exit_code}"
log_error " Location: ${func}() at ${src}:${line}"
log_error " Command: ${failed_cmd}"
# Print stack trace in verbose mode
if [[ ${VERBOSE} == true ]]; then
log_debug "Stack trace:"
local -i i
for ((i = 1; i < ${#FUNCNAME[@]}; i++)); do
log_debug " [${i}] ${FUNCNAME[i]}() at ${BASH_SOURCE[i]:-unknown}:${BASH_LINENO[i - 1]}"
done
# Show key variable state for debugging
log_debug "Variable state:"
log_debug " DRY_RUN=${DRY_RUN:-unset}"
log_debug " ARCH=${ARCH:-unset}"
log_debug " TARGET_USER=${TARGET_USER:-unset}"
fi
}
#-------------------------------------------------------------------------------
# Cleanup Handler (runs on EXIT - catches all termination scenarios)
#-------------------------------------------------------------------------------
# Kill any child processes in our process group
cleanup_processes() {
# Get list of child processes
local -a child_pids
mapfile -t child_pids < <(pgrep -P $$ 2>/dev/null || true)
if ((${#child_pids[@]} > 0)); then
log_debug "Terminating ${#child_pids[@]} child process(es)"
for pid in "${child_pids[@]}"; do
kill -TERM "${pid}" 2>/dev/null || true
done
# Brief wait for graceful termination
sleep 0.5
# Force kill any remaining
for pid in "${child_pids[@]}"; do
kill -KILL "${pid}" 2>/dev/null || true
done
fi
}
cleanup() {
local -ri original_exit_code=${?}
local -i exit_code=${original_exit_code}
# Prevent recursive cleanup
if ((CLEANUP_IN_PROGRESS)); then
return
fi
CLEANUP_IN_PROGRESS=1
# Disable all signal traps during cleanup to prevent interruption
trap '' INT TERM HUP QUIT
log_debug "Cleanup triggered (exit_code=${exit_code}, signal=${RECEIVED_SIGNAL:-none})"
# Terminate any child processes first
cleanup_processes
# If we received a fatal signal, adjust messaging
if [[ -n ${RECEIVED_SIGNAL} ]]; then
log_info "Cleaning up after SIG${RECEIVED_SIGNAL}..."
fi
# Execute registered cleanup actions in reverse order (LIFO)
local -i i
for ((i = ${#CLEANUP_ACTIONS[@]} - 1; i >= 0; i--)); do
local action="${CLEANUP_ACTIONS[i]}"
log_debug "Executing cleanup action: ${action}"
if declare -F "${action}" &>/dev/null; then
"${action}" 2>/dev/null || true
else
log_warn "Unknown cleanup action skipped: ${action}"
fi
done
# Rollback: Remove files we created (if exit was not successful)
if ((exit_code != 0)); then
log_info "Rolling back changes..."
for file in "${!CREATED_FILES[@]}"; do
if [[ -f ${file} ]]; then
log_debug "Removing created file: ${file}"
rm -f "${file}" 2>/dev/null || true
fi
done
# Restore modified files from backups
for file in "${!MODIFIED_FILES[@]}"; do
local backup="${MODIFIED_FILES[${file}]}"
if [[ -f ${backup} ]]; then
log_debug "Restoring ${file} from ${backup}"
mv -f "${backup}" "${file}" 2>/dev/null || true
fi
done
# Clean up apt state if we were mid operation
local has_apt=false
# shellcheck disable=SC2310 # Intentional: capture result in variable
has_command apt-get && has_apt=true
if [[ ${has_apt} == true ]]; then
log_debug "Cleaning apt state..."
apt-get clean 2>/dev/null || true
rm -f /var/lib/apt/lists/lock 2>/dev/null || true
rm -f /var/lib/dpkg/lock* 2>/dev/null || true
fi
else
# Success: remove backup files
for file in "${!MODIFIED_FILES[@]}"; do
local backup="${MODIFIED_FILES[${file}]}"
rm -f "${backup}" 2>/dev/null || true
done
fi
# Final status
if ((exit_code != 0)); then
log_error "Script failed with exit code: ${exit_code}"
[[ -n ${RECEIVED_SIGNAL} ]] && log_error "Terminated by: SIG${RECEIVED_SIGNAL}"
log_info "Log file: ${LOG_FILE}"
fi
exit "${exit_code}"
}
#-------------------------------------------------------------------------------
# Setup Signal Handlers
#-------------------------------------------------------------------------------
setup_signal_handlers() {
# EXIT trap - always runs, handles all cleanup
trap cleanup EXIT
# ERR trap - provides error context
trap error_handler ERR
# Graceful termination signals
trap 'signal_handler HUP' HUP
trap 'signal_handler INT' INT
trap 'signal_handler QUIT' QUIT
trap 'signal_handler TERM' TERM
# Program error signals (fatal - attempt cleanup)
trap 'signal_handler ILL' ILL
trap 'signal_handler TRAP' TRAP
trap 'signal_handler ABRT' ABRT
trap 'signal_handler BUS' BUS
trap 'signal_handler FPE' FPE
trap 'signal_handler SEGV' SEGV
trap 'signal_handler SYS' SYS
trap 'signal_handler STKFLT' STKFLT 2>/dev/null || true
# These are not widely available. Attempt to trap but ignore failure
trap 'signal_handler EMT' EMT 2>/dev/null || true
trap 'signal_handler IOT' IOT 2>/dev/null || true
log_debug "Signal handlers installed"
}
#-------------------------------------------------------------------------------
# Validation Functions
#-------------------------------------------------------------------------------
check_root() {
((EUID == 0)) || die "This script must be run as root. Use: sudo ${SCRIPT_NAME}" "${EXIT_ROOT_REQUIRED}"
}
check_wsl2() {
log_info "Checking WSL2 environment..."
# shellcheck disable=SC2310 # Intentional: die terminates on failure
is_wsl2 || die "This script requires WSL2. Detected non-WSL2 system." "${EXIT_NOT_WSL2}"
log_success "WSL2 environment confirmed"
}
detect_architecture() {
log_info "Detecting system architecture..."
local machine
machine="$(uname -m)" || die "Failed to detect architecture" "${EXIT_GENERAL_ERROR}"
local -r machine
case "${machine}" in
x86_64) ARCH="amd64" ;;
aarch64 | arm64) ARCH="arm64" ;;
armv7l | armhf) ARCH="armhf" ;;
*) die "Unsupported architecture: ${machine}" "${EXIT_UNSUPPORTED_DISTRO}" ;;
esac
log_success "Architecture: ${ARCH}"
}
validate_user() {
log_info "Validating target user..."
[[ -z ${TARGET_USER} ]] && TARGET_USER="${SUDO_USER:-${USER:-}}"
if [[ -z ${TARGET_USER} || ${TARGET_USER} == root ]]; then
die "A non-root user must be specified with --user USERNAME" "${EXIT_INVALID_ARGS}"
fi
id "${TARGET_USER}" &>/dev/null || die "User '${TARGET_USER}' does not exist" "${EXIT_INVALID_ARGS}"
log_success "Target user: ${TARGET_USER}"
}
#-------------------------------------------------------------------------------
# Network Connectivity Check
#-------------------------------------------------------------------------------
check_network() {
log_info "Checking network connectivity..."
local -ra test_endpoints=(
"https://cli.github.com"
"https://github.com"
)
local endpoint
for endpoint in "${test_endpoints[@]}"; do
if curl -fsSL \
--proto '=https' \
--tlsv1.2 \
--connect-timeout 5 \
--max-time 10 \
-o /dev/null \
"${endpoint}" 2>/dev/null; then
log_success "Network connectivity confirmed"
return 0
fi
done
die "No network connectivity. Please check your internet connection." "${EXIT_NETWORK_ERROR}"
}
#-------------------------------------------------------------------------------
# GitHub CLI Installation Functions
#-------------------------------------------------------------------------------
setup_gh_repository() {
log_step "1/6" "Setting up GitHub CLI repository"
local -r keyring_dir="/etc/apt/keyrings"
local -r keyring_file="${keyring_dir}/githubcli-archive-keyring.gpg"
local -r sources_file="/etc/apt/sources.list.d/github-cli.sources"
# Create keyring directory if needed
[[ -d ${keyring_dir} ]] || execute install -m 0755 -d "${keyring_dir}"
# Check for existing valid setup
if [[ -f ${keyring_file} && -f ${sources_file} ]]; then
# shellcheck disable=SC2310 # Intentional: check function result in conditional
if verify_gpg_fingerprint "${keyring_file}" 2>/dev/null; then
log_success "GitHub CLI repository already configured"
return 0
fi
log_warn "Existing GPG key invalid, refreshing..."
fi
log_info "Downloading GitHub CLI GPG key..."
if [[ ${DRY_RUN} == true ]]; then
log_info "[DRY-RUN] Would download: ${GH_GPG_URL}"
return 0
fi
retry_with_backoff "${MAX_RETRIES}" "${RETRY_DELAY_BASE}" \
secure_download "${GH_GPG_URL}" "${keyring_file}" 1048576
chmod a+r "${keyring_file}"
verify_gpg_fingerprint "${keyring_file}"
register_created_file "${keyring_file}"
# Create DEB822 format sources file
log_info "Configuring repository..."
local repo_content
printf -v repo_content 'Types: deb
URIs: %s
Suites: stable
Components: main
Signed-By: %s
Architectures: %s' \
"${GH_REPO_URL}" "${keyring_file}" "${ARCH}"
[[ -f ${sources_file} ]] && backup_file "${sources_file}"
atomic_write "${sources_file}" "${repo_content}"
log_info "Updating package index..."
execute apt-get update -qq
log_success "GitHub CLI repository configured"
}
install_github_cli() {
log_step "2/6" "Installing GitHub CLI"
# Check existing installation
local has_gh=false
# shellcheck disable=SC2310 # Intentional: capture result in variable
has_command gh && has_gh=true
if [[ ${has_gh} == true ]]; then
local current_version
current_version="$(gh --version 2>/dev/null | head -1)" || current_version="unknown"
log_info "GitHub CLI already installed: ${current_version}"
if sudo -u "${TARGET_USER}" gh auth status &>/dev/null; then
log_success "GitHub CLI is authenticated and functional"
else
log_info "GitHub CLI installed but not authenticated"
fi
return 0
fi
log_info "Installing: gh"
if [[ ${DRY_RUN} == true ]]; then
log_info "[DRY-RUN] Would install: gh"
return 0
fi
execute apt_install gh
# shellcheck disable=SC2310 # Intentional: die terminates on failure
has_command gh || die "GitHub CLI installation failed" "${EXIT_INSTALL_FAILED}"
local gh_ver
gh_ver="$(gh --version | head -1)" || gh_ver="unknown"
log_success "GitHub CLI installed: ${gh_ver}"
}
authenticate_github() {
log_step "3/6" "Authenticating with GitHub"
# Check if already authenticated
if sudo -u "${TARGET_USER}" gh auth status &>/dev/null; then
log_success "Already authenticated with GitHub"
return 0
fi
if [[ ${DRY_RUN} == true ]]; then
log_info "[DRY-RUN] Would run: gh auth login --hostname github.com --git-protocol https --web"
return 0
fi
# Check if we have a TTY for interactive auth
if [[ ! -t 0 ]]; then
log_warn "No interactive terminal detected"
log_warn "GitHub authentication requires browser interaction"
log_warn "Options:"
log_warn " 1. Run this script in an interactive terminal"
log_warn " 2. Pre-authenticate: sudo -u ${TARGET_USER} gh auth login"
log_warn " 3. Use token: echo TOKEN | sudo -u ${TARGET_USER} gh auth login --with-token"
die "Interactive authentication required" "${EXIT_AUTH_FAILED}"
fi
log_info "Starting browser-based OAuth authentication..."
log_warn "INTERACTIVE: A browser window will open for GitHub authentication"
log_info ""
log_info "Authentication settings:"
log_info " - Host: github.com"
log_info " - Protocol: HTTPS"
log_info " - Git authentication: Enabled"
log_info ""
# Run gh auth login as the target user
# This is interactive and requires user browser action
# Note: admin:public_key scope is required for gh ssh-key add
# Set browser for WSL2 - use Windows explorer.exe to open URLs
# Must use full path because appendWindowsPath=false in /etc/wsl.conf
local -r windows_browser="/mnt/c/Windows/explorer.exe"
if [[ ! -x "${windows_browser}" ]]; then
log_warn "Windows explorer.exe not found at ${windows_browser}"
log_warn "Browser may not open automatically - copy the URL manually"
fi
if ! sudo -u "${TARGET_USER}" GH_BROWSER="${windows_browser}" gh auth login \
--hostname github.com \
--git-protocol https \
--web \
--scopes admin:public_key; then
die "GitHub authentication failed" "${EXIT_AUTH_FAILED}"
fi
# Verify authentication
if ! sudo -u "${TARGET_USER}" gh auth status &>/dev/null; then
die "Authentication verification failed" "${EXIT_AUTH_FAILED}"
fi
# Setup Git to use gh for authentication
sudo -u "${TARGET_USER}" gh auth setup-git
log_success "GitHub authentication complete"
}
configure_git_identity() {
log_step "4/6" "Configuring Git identity"
if [[ ${SKIP_GIT_CONFIG} == true ]]; then
log_info "Skipping Git configuration (--skip-git-config)"
return 0
fi
# Check if already configured
local existing_name existing_email
existing_name=$(sudo -u "${TARGET_USER}" git config --global user.name 2>/dev/null) || true
existing_email=$(sudo -u "${TARGET_USER}" git config --global user.email 2>/dev/null) || true
if [[ -n ${existing_name} && -n ${existing_email} ]]; then
log_info "Git already configured:"
log_info " user.name: ${existing_name}"
log_info " user.email: ${existing_email}"
log_success "Git identity already configured"
return 0
fi
if [[ ${DRY_RUN} == true ]]; then
log_info "[DRY-RUN] Would configure Git identity from GitHub API"
return 0
fi