Repository navigation
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·1425 lines (1256 loc) · 44.4 KB
/
Copy pathinstall.sh
File metadata and controls
executable file
·1425 lines (1256 loc) · 44.4 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
#!/bin/bash
# Detect if script is being sourced or executed
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
SCRIPT_SOURCED=0 # Script is being executed
else
SCRIPT_SOURCED=1 # Script is being sourced
# Save original shell options to restore later
ORIGINAL_SHELL_OPTS=$(set +o)
fi
set -euo pipefail
# =============================================================================
# Configuration
# =============================================================================
INSTALL_LOG="$HOME/.config/cli-setup-install.log"
STATE_FILE="$HOME/.config/cli-setup/state.json"
INSTALLED_VERSION_FILE="$HOME/.config/cli-setup/version"
BACKUP_DIR="$HOME/.config/cli-setup/backups/$(date +%Y%m%d-%H%M%S)"
MANIFEST_URL="https://raw.githubusercontent.com/agileguy/cli-setup/main/manifest.json"
GITHUB_RAW_BASE="https://raw.githubusercontent.com/agileguy/cli-setup/main"
REPO_VERSION_API_URL="https://api.github.com/repos/agileguy/cli-setup/contents/VERSION"
# Default options
INSTALL_MODE="full" # full or shell
VERBOSE=0
DRY_RUN=0
SKIP_BACKUP=0
FORCE_INSTALL=0
USE_LOCAL=0
LOCAL_DIR=""
CHECK_ONLY=0
INTERACTIVE=0
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# =============================================================================
# Argument Parsing
# =============================================================================
show_help() {
cat << EOF
Usage: install.sh [OPTIONS]
Options:
--shell-only Install shell tools only (no desktop/GUI components)
--verbose, -v Show detailed output
--dry-run Show what would be installed without making changes
--skip-backup Skip backing up existing config files
--force Force reinstall even if already at latest version
--local DIR Use local files from DIR instead of downloading
--check Run pre-flight checks only (no installation)
--interactive Interactive mode with prompts and confirmations
--help, -h Show this help message
Examples:
./install.sh # Full installation
./install.sh --shell-only # Shell tools only
./install.sh --dry-run # Preview what would be installed
./install.sh --force # Force reinstall
./install.sh --local . # Use local repo files (offline mode)
./install.sh --check # Validate system before installing
./install.sh --interactive # Guided installation with prompts
. install.sh --shell-only # Source for auto shell config
EOF
}
while [[ $# -gt 0 ]]; do
case $1 in
--shell-only)
INSTALL_MODE="shell"
shift
;;
--verbose|-v)
VERBOSE=1
shift
;;
--dry-run)
DRY_RUN=1
shift
;;
--skip-backup)
SKIP_BACKUP=1
shift
;;
--force)
FORCE_INSTALL=1
shift
;;
--check)
CHECK_ONLY=1
VERBOSE=1 # Enable verbose output for check mode
shift
;;
--interactive|-i)
INTERACTIVE=1
shift
;;
--local)
USE_LOCAL=1
LOCAL_DIR="$2"
if [ -z "$LOCAL_DIR" ] || [ ! -d "$LOCAL_DIR" ]; then
echo "Error: --local requires a valid directory"
exit 1
fi
# Convert to absolute path
LOCAL_DIR=$(cd "$LOCAL_DIR" && pwd)
shift 2
;;
--help|-h)
show_help
if [ "$SCRIPT_SOURCED" -eq 1 ]; then
return 0
else
exit 0
fi
;;
*)
echo "Unknown option: $1"
show_help
if [ "$SCRIPT_SOURCED" -eq 1 ]; then
return 1
else
exit 1
fi
;;
esac
done
# =============================================================================
# Logging Functions
# =============================================================================
mkdir -p "$(dirname "$INSTALL_LOG")"
mkdir -p "$(dirname "$STATE_FILE")"
log_info() {
echo -e "${BLUE}[INFO]${NC} $1" | tee -a "$INSTALL_LOG"
}
log_success() {
echo -e "${GREEN}[OK]${NC} $1" | tee -a "$INSTALL_LOG"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1" | tee -a "$INSTALL_LOG"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1" | tee -a "$INSTALL_LOG"
}
log_verbose() {
if [ "$VERBOSE" -eq 1 ]; then
echo -e "${BLUE}[DEBUG]${NC} $1" | tee -a "$INSTALL_LOG"
fi
}
log_dry_run() {
if [ "$DRY_RUN" -eq 1 ]; then
echo -e "${YELLOW}[DRY-RUN]${NC} Would: $1"
fi
}
# =============================================================================
# Error Handling
# =============================================================================
if [ "$SKIP_BACKUP" -eq 0 ]; then
mkdir -p "$BACKUP_DIR"
fi
cleanup_on_error() {
local exit_code=$?
local line_number=$1
echo "" | tee -a "$INSTALL_LOG"
log_error "Installation failed at line $line_number with exit code $exit_code"
log_error "See log file: $INSTALL_LOG"
if [ "$SKIP_BACKUP" -eq 0 ]; then
log_error "Backups saved to: $BACKUP_DIR"
fi
echo "" | tee -a "$INSTALL_LOG"
log_info "Cleaning up temporary files..."
# Clean up common temporary files
rm -f /tmp/lazygit.tar.gz /tmp/lazygit 2>/dev/null || true
# Use return if sourced, exit if executed
if [ "$SCRIPT_SOURCED" -eq 1 ]; then
eval "$ORIGINAL_SHELL_OPTS"
return "$exit_code"
else
exit "$exit_code"
fi
}
trap 'cleanup_on_error ${LINENO}' ERR
# =============================================================================
# Dependency Checking
# =============================================================================
check_dependencies() {
log_info "Checking system dependencies..."
local errors=0
# Check for apt (Debian/Ubuntu)
if ! command -v apt &> /dev/null; then
log_error "This script requires apt (Debian/Ubuntu-based system)"
errors=$((errors + 1))
else
log_verbose "apt package manager found"
fi
# Check for sudo access
if ! sudo -v 2>/dev/null; then
log_error "This script requires sudo access"
errors=$((errors + 1))
else
log_verbose "sudo access verified"
fi
# Check disk space (at least 2GB free)
local free_space
free_space=$(df -BG / | awk 'NR==2 {print $4}' | sed 's/G//')
if [ "$free_space" -lt 2 ]; then
log_error "Insufficient disk space: ${free_space}GB available, need at least 2GB"
errors=$((errors + 1))
else
log_verbose "Disk space OK: ${free_space}GB available"
fi
# Check internet connectivity
if ! curl -s --connect-timeout 5 https://github.com > /dev/null 2>&1; then
log_error "No internet connectivity (cannot reach github.com)"
errors=$((errors + 1))
else
log_verbose "Internet connectivity OK"
fi
# Check for jq (needed for manifest parsing)
if ! command -v jq &> /dev/null; then
log_warn "jq not installed - will install it first for manifest parsing"
if [ "$DRY_RUN" -eq 0 ]; then
sudo apt update && sudo apt install -y jq
fi
else
log_verbose "jq found for JSON parsing"
fi
if [ "$errors" -gt 0 ]; then
log_error "Dependency check failed with $errors error(s)"
if [ "$SCRIPT_SOURCED" -eq 1 ]; then
return 1
else
exit 1
fi
fi
log_success "All dependencies satisfied"
}
# =============================================================================
# Pre-flight System Check (--check mode)
# =============================================================================
check_system() {
local warnings=0
local errors=0
echo ""
log_info "=== Pre-flight System Check ==="
echo ""
# OS Detection
log_info "Operating System:"
if [ -f /etc/os-release ]; then
. /etc/os-release
log_verbose " Distribution: $NAME $VERSION"
if [[ "$ID" != "ubuntu" && "$ID" != "debian" && "$ID_LIKE" != *"debian"* ]]; then
log_warn " Non-Debian/Ubuntu system detected - some packages may not install"
warnings=$((warnings + 1))
else
log_success " Debian/Ubuntu-based system detected"
fi
else
log_warn " Could not detect OS distribution"
warnings=$((warnings + 1))
fi
# Architecture
local arch=$(uname -m)
log_verbose " Architecture: $arch"
if [[ "$arch" != "x86_64" ]]; then
log_warn " Non-x86_64 architecture - some binaries may not be available"
warnings=$((warnings + 1))
fi
# Display server (for desktop install)
echo ""
log_info "Display Environment:"
if [ "$INSTALL_MODE" = "full" ]; then
if [ -n "$DISPLAY" ]; then
log_success " X11 display detected: $DISPLAY"
elif [ -n "$WAYLAND_DISPLAY" ]; then
log_warn " Wayland display detected - i3/picom require X11"
warnings=$((warnings + 1))
else
log_warn " No display server detected - desktop components may not work"
warnings=$((warnings + 1))
fi
else
log_verbose " Shell-only mode - display server not required"
fi
# Package managers
echo ""
log_info "Package Managers:"
if command -v apt &> /dev/null; then
log_success " apt: Available"
else
log_error " apt: Not found (required)"
errors=$((errors + 1))
fi
if command -v snap &> /dev/null; then
log_success " snap: Available"
else
log_warn " snap: Not found (will be installed via apt)"
warnings=$((warnings + 1))
fi
if command -v flatpak &> /dev/null; then
log_success " flatpak: Available"
else
if [ "$INSTALL_MODE" = "full" ]; then
log_verbose " flatpak: Not found (will be installed)"
else
log_verbose " flatpak: Not found (not needed for shell-only)"
fi
fi
# Disk space
echo ""
log_info "Disk Space:"
local free_space
free_space=$(df -BG / | awk 'NR==2 {print $4}' | sed 's/G//')
local required_space=2
if [ "$INSTALL_MODE" = "full" ]; then
required_space=5
fi
if [ "$free_space" -lt "$required_space" ]; then
log_error " Available: ${free_space}GB (need ${required_space}GB minimum)"
errors=$((errors + 1))
else
log_success " Available: ${free_space}GB (${required_space}GB required)"
fi
# Network connectivity
echo ""
log_info "Network Connectivity:"
local test_urls=("github.com" "raw.githubusercontent.com" "dl.flathub.org")
for url in "${test_urls[@]}"; do
if curl -s --connect-timeout 5 "https://$url" > /dev/null 2>&1; then
log_success " $url: Reachable"
else
if [ "$USE_LOCAL" -eq 1 ]; then
log_verbose " $url: Not reachable (offline mode enabled)"
else
log_warn " $url: Not reachable"
warnings=$((warnings + 1))
fi
fi
done
# Sudo access
echo ""
log_info "Permissions:"
if sudo -n true 2>/dev/null; then
log_success " sudo: Available (passwordless)"
elif sudo -v 2>/dev/null; then
log_success " sudo: Available (password required)"
else
log_error " sudo: Not available"
errors=$((errors + 1))
fi
# Existing installations
echo ""
log_info "Existing Installations:"
local existing_tools=0
for tool in nvim tmux git curl zoxide eza fzf lazygit; do
if command -v "$tool" &> /dev/null; then
log_verbose " $tool: Already installed"
existing_tools=$((existing_tools + 1))
fi
done
if [ "$existing_tools" -gt 0 ]; then
log_verbose " $existing_tools tools already installed (will be skipped)"
fi
# Check for conflicting packages
echo ""
log_info "Potential Conflicts:"
if command -v nvim &> /dev/null; then
local nvim_path=$(which nvim)
if [[ "$nvim_path" == *"snap"* ]]; then
log_verbose " nvim: Installed via snap (expected)"
elif [[ "$nvim_path" == "/opt/"* ]]; then
log_verbose " nvim: Installed from source/tarball"
else
log_verbose " nvim: Custom installation at $nvim_path"
fi
fi
# Version check
echo ""
log_info "Version:"
local installed_version=""
if [ -f "$INSTALLED_VERSION_FILE" ]; then
installed_version=$(cat "$INSTALLED_VERSION_FILE" | tr -d '[:space:]')
log_verbose " Installed version: $installed_version"
else
log_verbose " No previous installation detected"
fi
# Summary
echo ""
log_info "=== Check Summary ==="
if [ "$errors" -gt 0 ]; then
log_error "$errors error(s) found - installation may fail"
fi
if [ "$warnings" -gt 0 ]; then
log_warn "$warnings warning(s) found - review before proceeding"
fi
if [ "$errors" -eq 0 ] && [ "$warnings" -eq 0 ]; then
log_success "System ready for installation"
elif [ "$errors" -eq 0 ]; then
log_success "System can proceed with installation (with warnings)"
fi
echo ""
return "$errors"
}
# =============================================================================
# Interactive Mode Functions
# =============================================================================
prompt_yes_no() {
local prompt="$1"
local default="${2:-y}"
local response
if [ "$default" = "y" ]; then
prompt="$prompt [Y/n]: "
else
prompt="$prompt [y/N]: "
fi
read -r -p "$prompt" response
response=${response:-$default}
case "$response" in
[yY][eE][sS]|[yY]) return 0 ;;
*) return 1 ;;
esac
}
prompt_choice() {
local prompt="$1"
shift
local options=("$@")
local choice
echo "$prompt"
for i in "${!options[@]}"; do
echo " $((i+1))) ${options[$i]}"
done
while true; do
read -r -p "Enter choice [1-${#options[@]}]: " choice
if [[ "$choice" =~ ^[0-9]+$ ]] && [ "$choice" -ge 1 ] && [ "$choice" -le "${#options[@]}" ]; then
return $((choice - 1))
fi
echo "Invalid choice. Please enter a number between 1 and ${#options[@]}."
done
}
run_interactive_setup() {
echo ""
echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║${NC} ${GREEN}CLI Setup - Interactive Installation${NC} ${BLUE}║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""
# Installation mode
echo -e "${YELLOW}Step 1: Installation Mode${NC}"
prompt_choice "What would you like to install?" "Full installation (shell + desktop/i3)" "Shell tools only (no GUI components)"
local mode_choice=$?
if [ "$mode_choice" -eq 1 ]; then
INSTALL_MODE="shell"
log_info "Selected: Shell-only installation"
else
INSTALL_MODE="full"
log_info "Selected: Full installation"
fi
echo ""
# Backup preference
echo -e "${YELLOW}Step 2: Backup Options${NC}"
if prompt_yes_no "Create backups of existing config files?" "y"; then
SKIP_BACKUP=0
log_info "Backups will be created"
else
SKIP_BACKUP=1
log_info "Skipping backups"
fi
echo ""
# Verbose mode
echo -e "${YELLOW}Step 3: Output Verbosity${NC}"
if prompt_yes_no "Enable verbose output?" "n"; then
VERBOSE=1
log_info "Verbose mode enabled"
fi
echo ""
# Run pre-flight check
echo -e "${YELLOW}Step 4: System Check${NC}"
echo "Running pre-flight system check..."
echo ""
check_system
local check_result=$?
echo ""
if [ "$check_result" -gt 0 ]; then
echo -e "${RED}System check found errors.${NC}"
if ! prompt_yes_no "Continue anyway?" "n"; then
log_info "Installation cancelled by user"
if [ "$SCRIPT_SOURCED" -eq 1 ]; then
eval "$ORIGINAL_SHELL_OPTS"
return 1
else
exit 1
fi
fi
fi
# Final confirmation
echo -e "${YELLOW}Step 5: Confirmation${NC}"
echo ""
echo "Installation Summary:"
echo " - Mode: $INSTALL_MODE"
echo " - Backups: $([ "$SKIP_BACKUP" -eq 0 ] && echo "enabled" || echo "disabled")"
echo " - Verbose: $([ "$VERBOSE" -eq 1 ] && echo "enabled" || echo "disabled")"
echo ""
if ! prompt_yes_no "Proceed with installation?" "y"; then
log_info "Installation cancelled by user"
if [ "$SCRIPT_SOURCED" -eq 1 ]; then
eval "$ORIGINAL_SHELL_OPTS"
return 0
else
exit 0
fi
fi
echo ""
log_info "Starting installation..."
echo ""
}
show_installation_summary() {
echo ""
echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║${NC} ${GREEN}Installation Complete!${NC} ${BLUE}║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${GREEN}What was installed:${NC}"
echo " - Shell tools: git, tmux, nvim, fzf, lazygit, etc."
echo " - Shell enhancements: mcfly, zoxide, eza, bat"
echo " - Configuration: bashrc, tmux.conf, gitconfig, etc."
if [ "$INSTALL_MODE" = "full" ]; then
echo " - Desktop: i3, polybar, rofi, picom, kitty"
echo " - Backgrounds: Classic artwork with 5-min rotation"
fi
echo ""
echo -e "${YELLOW}Next steps:${NC}"
echo " 1. Open a new terminal or run: source ~/.bashrc"
if [ "$INSTALL_MODE" = "full" ]; then
echo " 2. Log out and select i3 as your session"
echo " 3. Press \$mod+d to open the application launcher"
fi
echo ""
echo -e "${BLUE}Useful commands:${NC}"
echo " - cc : Claude Code CLI"
echo " - lazygit : Terminal UI for git"
echo " - btop : System monitor"
echo " - ncdu : Disk usage analyzer"
if [ "$INSTALL_MODE" = "full" ]; then
echo " - \$mod+Return : Open terminal"
echo " - \$mod+d : Application launcher"
echo " - \$mod+Escape : Lock screen"
fi
echo ""
if [ "$SKIP_BACKUP" -eq 0 ]; then
echo -e "${BLUE}Backups saved to:${NC}"
echo " $BACKUP_DIR"
echo ""
fi
echo -e "${BLUE}Log file:${NC}"
echo " $INSTALL_LOG"
echo ""
}
# =============================================================================
# Version Checking
# =============================================================================
check_version() {
log_info "Checking version..."
# Get version (from local file or remote)
local remote_version
if [ "$USE_LOCAL" -eq 1 ]; then
if [ -f "$LOCAL_DIR/VERSION" ]; then
remote_version=$(cat "$LOCAL_DIR/VERSION" | tr -d '[:space:]')
else
log_warn "Local VERSION file not found, proceeding with installation"
return 0
fi
else
# Use GitHub API to avoid CDN caching issues
remote_version=$(curl -fsSL "$REPO_VERSION_API_URL" 2>/dev/null | jq -r '.content' | base64 -d | tr -d '[:space:]') || {
log_warn "Could not fetch remote version, proceeding with installation"
return 0
}
fi
# Get installed version (if exists)
local installed_version=""
if [ -f "$INSTALLED_VERSION_FILE" ]; then
installed_version=$(cat "$INSTALLED_VERSION_FILE" | tr -d '[:space:]')
fi
log_verbose "Remote version: $remote_version"
log_verbose "Installed version: ${installed_version:-none}"
# If force install, skip version check
if [ "$FORCE_INSTALL" -eq 1 ]; then
log_info "Force install requested, proceeding..."
return 0
fi
# Compare versions
if [ -n "$installed_version" ] && [ "$installed_version" = "$remote_version" ]; then
log_success "Already at latest version ($remote_version)"
log_info "Use --force to reinstall"
if [ "$SCRIPT_SOURCED" -eq 1 ]; then
eval "$ORIGINAL_SHELL_OPTS"
return 0
else
exit 0
fi
fi
if [ -n "$installed_version" ]; then
log_info "Upgrading from $installed_version to $remote_version"
else
log_info "Installing version $remote_version"
fi
}
# =============================================================================
# System Information Logging
# =============================================================================
log_system_info() {
log_info "System Information:"
log_verbose " OS: $(lsb_release -d 2>/dev/null | cut -f2 || cat /etc/os-release | grep PRETTY_NAME | cut -d'"' -f2)"
log_verbose " Kernel: $(uname -r)"
log_verbose " Architecture: $(uname -m)"
log_verbose " User: $(whoami)"
log_verbose " Home: $HOME"
log_verbose " Install Mode: $INSTALL_MODE"
}
# =============================================================================
# Helper Functions
# =============================================================================
is_installed() {
command -v "$1" &> /dev/null
}
backup_file() {
local file="$1"
if [ "$SKIP_BACKUP" -eq 1 ]; then
return 0
fi
if [ -f "$file" ]; then
local backup_path="$BACKUP_DIR${file}"
mkdir -p "$(dirname "$backup_path")"
cp "$file" "$backup_path"
log_verbose "Backed up: $file"
fi
}
verify_checksum() {
local file="$1"
local expected="$2"
if [ -z "$expected" ] || [ "$expected" = "SKIP" ]; then
log_verbose "Checksum verification skipped (relying on HTTPS)"
return 0
fi
log_verbose "Verifying checksum..."
local actual
actual=$(sha256sum "$file" | awk '{print $1}')
if [ "$actual" = "$expected" ]; then
log_verbose "Checksum verified"
return 0
else
log_error "Checksum mismatch! Expected: $expected, Got: $actual"
return 1
fi
}
expand_path() {
local path="$1"
# Expand ~ and $HOME
path="${path/#\~/$HOME}"
eval echo "$path"
}
# Validate path is safe (no directory traversal, within allowed directories)
validate_path() {
local path="$1"
local expanded_path
# Expand the path
expanded_path=$(expand_path "$path")
# Check for directory traversal attempts
if [[ "$expanded_path" =~ \.\. ]]; then
log_error "Path contains directory traversal: $path"
return 1
fi
# Ensure path starts with allowed prefixes
local allowed_prefixes=("$HOME" "/tmp" "/usr/local")
local is_allowed=0
for prefix in "${allowed_prefixes[@]}"; do
if [[ "$expanded_path" == "$prefix"* ]]; then
is_allowed=1
break
fi
done
if [ "$is_allowed" -eq 0 ]; then
log_error "Path outside allowed directories: $path"
return 1
fi
return 0
}
# Curl with retry and exponential backoff
curl_with_retry() {
local url="$1"
local output="$2"
local max_retries=3
local retry_delay=2
local attempt=1
local curl_opts="-fsSL --connect-timeout 30 --max-time 300"
while [ $attempt -le $max_retries ]; do
log_verbose "Download attempt $attempt/$max_retries: $url"
if curl $curl_opts -o "$output" "$url"; then
# Verify we got a non-empty file
if [ -s "$output" ]; then
log_verbose "Download successful"
return 0
else
log_warn "Downloaded file is empty"
fi
fi
if [ $attempt -lt $max_retries ]; then
log_warn "Download failed, retrying in ${retry_delay}s..."
sleep $retry_delay
retry_delay=$((retry_delay * 2)) # Exponential backoff
fi
attempt=$((attempt + 1))
done
log_error "Download failed after $max_retries attempts: $url"
return 1
}
# Safely create directory (check for symlink attacks)
safe_mkdir() {
local dir="$1"
local expanded_dir
expanded_dir=$(expand_path "$dir")
# Validate the path first
if ! validate_path "$dir"; then
return 1
fi
# Check if path exists and is a symlink (potential attack)
if [ -L "$expanded_dir" ]; then
log_error "Security: Path is a symlink, refusing to create: $dir"
return 1
fi
# Check parent directory for symlinks
local parent_dir=$(dirname "$expanded_dir")
if [ -L "$parent_dir" ] && [ "$parent_dir" != "$HOME" ]; then
log_error "Security: Parent directory is a symlink: $parent_dir"
return 1
fi
# Create directory
mkdir -p "$expanded_dir"
}
# =============================================================================
# Installation Functions
# =============================================================================
install_apt() {
local package="$1"
local cmd="${2:-$1}"
if is_installed "$cmd"; then
log_success "$package already installed"
else
if [ "$DRY_RUN" -eq 1 ]; then
log_dry_run "apt install $package"
else
log_info "Installing $package..."
sudo apt install -y "$package"
fi
fi
}
install_snap() {
local package="$1"
local options="${2:-}"
local cmd="${3:-$1}"
if is_installed "$cmd"; then
log_success "$package already installed"
else
if [ "$DRY_RUN" -eq 1 ]; then
log_dry_run "snap install $package $options"
else
log_info "Installing $package via snap..."
sudo snap install "$package" $options
fi
fi
}
install_flatpak() {
local app_id="$1"
local cmd="${2:-}"
if [ -n "$cmd" ] && is_installed "$cmd"; then
log_success "$app_id already installed"
elif flatpak list --app 2>/dev/null | grep -q "$app_id"; then
log_success "$app_id already installed"
else
if [ "$DRY_RUN" -eq 1 ]; then
log_dry_run "flatpak install $app_id"
else
log_info "Installing $app_id via flatpak..."
sudo flatpak install -y flathub "$app_id"
fi
fi
}
clone_repo() {
local repo="$1"
local dest="$2"
dest=$(expand_path "$dest")
if [ -d "$dest" ]; then
log_success "$dest already exists"
else
if [ "$DRY_RUN" -eq 1 ]; then
log_dry_run "git clone $repo $dest"
else
log_info "Cloning $repo..."
git clone "$repo" "$dest"
fi
fi
}
connect_snap() {
local snap="$1"
local plug="$2"
local slot="${3:-}"
# Check if already connected
if snap connections "$snap" 2>/dev/null | grep -q "$plug.*$slot"; then
log_verbose "Snap connection $snap:$plug already exists"
return 0
fi
if [ "$DRY_RUN" -eq 1 ]; then
log_dry_run "snap connect $snap:$plug $slot"
else
log_info "Connecting $snap:$plug..."
sudo snap connect "$snap:$plug" $slot || log_warn "Could not connect $snap:$plug"
fi
}
download_config() {
local url="$1"
local dest="$2"
local cache_control="${3:-false}"
local executable="${4:-false}"
dest=$(expand_path "$dest")
# Validate destination path
if ! validate_path "$dest"; then
log_error "Refusing to download to unsafe path: $dest"
return 1
fi
safe_mkdir "$(dirname "$dest")"
backup_file "$dest"
if [ "$DRY_RUN" -eq 1 ]; then
if [ "$USE_LOCAL" -eq 1 ]; then
log_dry_run "copy local file -> $dest"
else
log_dry_run "curl $url -> $dest"
fi
else
if [ "$USE_LOCAL" -eq 1 ]; then
# Extract relative path from URL and copy from local directory
local rel_path="${url#$GITHUB_RAW_BASE/}"
local local_file="$LOCAL_DIR/$rel_path"
if [ -f "$local_file" ]; then
log_verbose "Copying local file: $rel_path"
cp "$local_file" "$dest"
else
log_error "Local file not found: $local_file"
return 1
fi
else
log_verbose "Downloading $(basename "$dest")..."
if ! curl_with_retry "$url" "$dest"; then
return 1
fi
fi
if [ "$executable" = "true" ]; then
chmod +x "$dest"
fi
fi
}
# =============================================================================
# Main Installation
# =============================================================================
main() {
echo "=== CLI Setup Installation Started at $(date) ===" | tee "$INSTALL_LOG"
echo "" | tee -a "$INSTALL_LOG"
log_info "Installation mode: $INSTALL_MODE"
if [ "$USE_LOCAL" -eq 1 ]; then
log_info "Using local files from: $LOCAL_DIR"
fi
if [ "$DRY_RUN" -eq 1 ]; then
log_warn "DRY RUN MODE - No changes will be made"
fi
echo ""
# Run pre-flight check if --check mode
if [ "$CHECK_ONLY" -eq 1 ]; then
check_system
local check_result=$?
if [ "$SCRIPT_SOURCED" -eq 1 ]; then
eval "$ORIGINAL_SHELL_OPTS"
return "$check_result"
else
exit "$check_result"
fi
fi