-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsetup.sh
More file actions
executable file
·1737 lines (1538 loc) · 48.7 KB
/
setup.sh
File metadata and controls
executable file
·1737 lines (1538 loc) · 48.7 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
#
# Development Environment Setup Script
# ==================================
#
# A comprehensive setup script for development environments on macOS and Linux.
# This script handles the installation and configuration of various development
# tools, programming languages, and utilities.
#
# Features:
# ---------
# - Cross-platform support (macOS and Linux)
# - Modular installation options
# - Extensive error handling and logging
# - XDG Base Directory compliance
# - Flexible configuration file management
# * Automatic backup of existing configurations
# * Optional installation of dotfiles
# * XDG-compliant config placement
# - System-specific optimizations
#
# Usage:
# ------
# ./setup.sh [OPTIONS] COMMAND
#
# Commands:
# all Install everything (recommended for new systems)
# basic Install basic development tools
# gui Install GUI applications
# program Install programming languages
# vim Configure Vim editor and plugins
# configs Install configuration files (or specify a specific config)
# configs Install configuration files only
#
# Options:
# -h, --help Show this help message
# -v, --verbose Enable verbose output
# -f, --force Force installation
# -n, --dry-run Show what would be done
# --config FILE Use custom config file
#
# Configuration:
# -------------
# The script can be configured via ~/.config/dotfiles/setup.conf
#
# Key configuration options:
# - INSTALL_CONFIGS: Control installation of dotfiles (true/false)
# - See README.md for all configuration options
#
# Log Files:
# ----------
# - Logs are stored in ~/.local/state/dotfiles/logs/
# - Log rotation is automatic (keeps last 5 logs)
# - Old logs are compressed after 7 days
#
# Dependencies:
# ------------
# - bash 4.0+ (macOS users might need to upgrade)
# - curl or wget
# - git
# - sudo (for system package installation)
#
# Platform-Specific Notes:
# ----------------------
# macOS:
# - Installs and uses Homebrew
# - Installs GNU utilities
# - Configures macOS-specific GUI apps
#
# Linux:
# - Supports apt and pacman
# - Configures Wayland/X11 environments
# - Sets up input methods
#
# Security:
# ---------
# - Downloads are verified when possible
# - Configurations are backed up before modification
# - Permissions are preserved during installation
#
# Return Codes:
# ------------
# 0: Success
# 1: General error
# 2: Invalid argument
# 3: Permission denied
# 4: Required tool missing
#
# Author: Lee (loyalpartner@163.com)
# Version: 2.0.0
# License: MIT
# Repository: https://github.com/loyalpartner/dotfiles
#
# For complete documentation, see: https://github.com/loyalpartner/dotfiles/README.md
# Enable strict mode
set -euo pipefail
[[ "${TRACE:-0}" == "1" ]] && set -x
#######################################
# Check if a command is available
# Arguments:
# Command to check
# Returns:
# 0 if command exists, 1 otherwise
#######################################
is_executable() {
command -v "$1" >/dev/null 2>&1
}
#######################################
# Check minimal dependencies for config installation
# Arguments:
# None
#######################################
check_dependencies_minimal() {
local failed=false
# Check for essential commands
for cmd in mkdir ln rm cp chmod; do
if ! is_executable "$cmd"; then
error "Required command not found: $cmd"
failed=true
fi
done
# Check write permissions in required directories
for dir in "${XDG_CONFIG_HOME}" "${APP_LOG_DIR}" "${BACKUP_DIR}"; do
if ! mkdir -p "${dir}" 2>/dev/null; then
error "Cannot create directory: ${dir}"
failed=true
fi
done
if [[ "$failed" == "true" ]]; then
error "Missing required dependencies or permissions"
exit 1
fi
debug_log "Minimal dependency check completed"
}
# Script constants
readonly SCRIPT_VERSION="2.0.0"
readonly SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
readonly START_TIME=$(date +%s)
# XDG Base Directories (with fallbacks)
readonly XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
readonly XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}"
readonly XDG_STATE_HOME="${XDG_STATE_HOME:-$HOME/.local/state}"
readonly XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}"
# Application directories and files
readonly APP_NAME="dotfiles"
readonly APP_STATE_DIR="${XDG_STATE_HOME}/${APP_NAME}"
readonly APP_LOG_DIR="${APP_STATE_DIR}/logs"
readonly APP_CACHE_DIR="${XDG_CACHE_HOME}/${APP_NAME}"
readonly LOG_FILE="${APP_LOG_DIR}/setup_$(date +%Y%m%d_%H%M%S).log"
#######################################
# Set up logging
# Arguments:
# None
#######################################
setup_logging() {
mkdir -p "$(dirname "${LOG_FILE}")"
touch "${LOG_FILE}"
# Ensure log directory has correct permissions
chmod 755 "$(dirname "${LOG_FILE}")"
}
#######################################
# Log an info message
# Arguments:
# Message to log
#######################################
info() {
echo -e "\033[0;32m[INFO]\033[0m $*"
echo "[INFO] $*" >> "${LOG_FILE}"
}
#######################################
# Log a warning message
# Arguments:
# Message to log
#######################################
warning() {
echo -e "\033[0;33m[WARN]\033[0m $*" >&2
echo "[WARN] $*" >> "${LOG_FILE}"
}
#######################################
# Log an error message
# Arguments:
# Message to log
#######################################
error() {
echo -e "\033[0;31m[ERROR]\033[0m $*" >&2
echo "[ERROR] $*" >> "${LOG_FILE}"
}
#######################################
# Log a debug message if debug is enabled
# Arguments:
# Message to log
#######################################
debug_log() {
if [[ "${DEBUG_ENABLE}" == "1" ]]; then
echo -e "\033[0;34m[DEBUG]\033[0m $*" >&2
echo "[DEBUG] $*" >> "${LOG_FILE}"
fi
}
# Files
readonly CONFIG_FILE="${XDG_CONFIG_HOME}/${APP_NAME}/setup.conf"
readonly TMP_DIR="$(mktemp -d)"
# Configuration paths
readonly CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}"
readonly VIM_HOME="$HOME/.vim"
readonly EMACS_HOME="$HOME/.emacs.d"
readonly OHMYZSH_HOME="$HOME/.oh-my-zsh"
readonly ZSH_CUSTOM="${ZSH_CUSTOM:-$OHMYZSH_HOME/custom}"
readonly NVM_HOME="$CONFIG_HOME/nvm"
readonly BACKUP_DIR="${HOME}/.config_backup/$(date +%Y%m%d_%H%M%S)"
# Repository URLs
readonly REPO_OHMYZSH="https://github.com/ohmyzsh/ohmyzsh"
readonly REPO_DOOM="https://github.com/hlissner/doom-emacs"
readonly REPO_P10K="https://github.com/romkatv/powerlevel10k.git"
readonly REPO_ZSH_SUGGESTION="https://github.com/zsh-users/zsh-autosuggestions"
readonly REPO_ZSH_LXD="https://github.com/endaaman/lxd-completion-zsh"
readonly URL_PLUG="https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim"
# Color definitions
readonly COLOR_ERROR='\033[0;31m'
readonly COLOR_INFO='\033[0;32m'
readonly COLOR_WARN='\033[0;33m'
readonly COLOR_DEBUG='\033[0;34m'
readonly COLOR_RESET='\033[0m'
# Default configuration values
DEBUG_ENABLE="${DEBUG_ENABLE:-0}"
VERBOSE="${VERBOSE:-0}"
DRY_RUN="${DRY_RUN:-0}"
FORCE_INSTALL="${FORCE_INSTALL:-0}"
PROXY_ENABLED="${PROXY_ENABLED:-0}"
PROXY_URL="${PROXY_URL:-http://127.0.0.1:7890}"
# Installation flags
INSTALL_BASIC=true
INSTALL_GUI=false
INSTALL_WAYLAND=false
INSTALL_PROGRAMMING=false
INSTALL_CHROMIUM_DEV=false
INSTALL_DOOM=false
INSTALL_VIM=true
INSTALL_CONFIGS=true
SETUP_ZSH=false
# System behavior flags
CHECK_NETWORK=false # Only check network if explicitly requested
INSTALLING_PACKAGES=false
# Programming language flags
INSTALL_PYTHON=false
INSTALL_NODE=false
INSTALL_GO=false
INSTALL_RUST=false
INSTALL_C=false
#######################################
# Print elapsed time since script start
# Arguments:
# None
#######################################
show_elapsed_time() {
local end_time=$(date +%s)
local elapsed=$((end_time - START_TIME))
info "Total execution time: $elapsed seconds"
}
#######################################
# Log a debug message if debug is enabled
# Arguments:
# Message text
#######################################
debug_log() {
[[ "${DEBUG_ENABLE}" == "1" ]] && echo -e "${COLOR_DEBUG}[DEBUG] $*${COLOR_RESET}"
[[ "${VERBOSE}" == "1" ]] && echo -e "${COLOR_DEBUG}[DEBUG] $*${COLOR_RESET}"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] [DEBUG] $*" >> "${LOG_FILE}"
}
#######################################
# Log an informational message
# Arguments:
# Message text
#######################################
info() {
echo -e "${COLOR_INFO}[INFO] $*${COLOR_RESET}"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] [INFO] $*" >> "${LOG_FILE}"
}
#######################################
# Log a warning message to stderr
# Arguments:
# Message text
#######################################
warn() {
echo -e "${COLOR_WARN}[WARN] $*${COLOR_RESET}" >&2
echo "[$(date '+%Y-%m-%d %H:%M:%S')] [WARN] $*" >> "${LOG_FILE}"
}
#######################################
# Log an error message to stderr
# Arguments:
# Message text
#######################################
error() {
echo -e "${COLOR_ERROR}[ERROR] $*${COLOR_RESET}" >&2
echo "[$(date '+%Y-%m-%d %H:%M:%S')] [ERROR] $*" >> "${LOG_FILE}"
}
#######################################
# Handle script errors
# Arguments:
# Exit code
# Line number where error occurred
#######################################
handle_error() {
local exit_code=$1
local line_no=$2
error "Error occurred in script at line ${line_no}, exit code: ${exit_code}"
case $exit_code in
1) error "General error occurred" ;;
2) error "Invalid argument or option" ;;
126) error "Command invoked cannot execute" ;;
127) error "Command not found" ;;
128) error "Invalid argument to exit" ;;
129) error "SIGHUP signal received" ;;
130) error "SIGINT signal received" ;;
131) error "SIGQUIT signal received" ;;
137) error "SIGKILL signal received" ;;
143) error "SIGTERM signal received" ;;
255) error "Exit status out of range" ;;
*) error "Unknown error occurred" ;;
esac
cleanup
exit "$exit_code"
}
#######################################
# Handle interrupt signal
# Arguments:
# None
#######################################
handle_interrupt() {
error "Interrupt signal received, cleaning up..."
cleanup
exit 130
}
#######################################
# Clean old cache files
# Arguments:
# None
#######################################
clean_old_cache() {
if [[ -d "${APP_CACHE_DIR}" ]]; then
local old_files
if is_macos; then
# On macOS, use stat to get access time
old_files=$(find "${APP_CACHE_DIR}" -type f -exec bash -c '
now=$(date +%s)
atime=$(stat -f %a "$1")
age=$(( (now - atime) / 86400 ))
if [ $age -gt 30 ]; then echo "$1"; fi
' bash {} \;)
else
# On Linux, we can use -atime directly
old_files=$(find "${APP_CACHE_DIR}" -type f -atime +30)
fi
# Remove old files
if [[ -n "${old_files}" ]]; then
echo "${old_files}" | while read -r file; do
if [[ -f "${file}" ]]; then
rm -f "${file}"
fi
done
fi
# Remove empty directories
find "${APP_CACHE_DIR}" -type d -empty -delete
fi
}
#######################################
# Compress old log files
# Arguments:
# None
#######################################
compress_old_logs() {
if [[ -d "${APP_LOG_DIR}" ]]; then
local files_to_compress
if is_macos; then
# On macOS, use stat to get file age
files_to_compress=$(find "${APP_LOG_DIR}" -type f -name "*.log" -exec bash -c '
now=$(date +%s)
fdate=$(stat -f %m "$1")
age=$(( (now - fdate) / 86400 ))
if [ $age -gt 7 ]; then echo "$1"; fi
' bash {} \;)
else
# On Linux, we can use -mtime directly
files_to_compress=$(find "${APP_LOG_DIR}" -type f -name "*.log" -mtime +7)
fi
if [[ -n "${files_to_compress}" ]]; then
echo "${files_to_compress}" | while read -r file; do
if [[ -f "${file}" ]]; then
gzip -f "${file}"
fi
done
fi
fi
}
#######################################
# Cleanup function called on script exit
# Arguments:
# None
#######################################
cleanup() {
local exit_code=$?
# Remove temporary directory
if [[ -d "${TMP_DIR}" ]]; then
rm -rf "${TMP_DIR}"
debug_log "Removed temporary directory: ${TMP_DIR}"
fi
# Clean old cache files
clean_old_cache
# Compress old logs
compress_old_logs
# Show completion message and elapsed time
if [[ $exit_code -eq 0 ]]; then
info "Script execution completed successfully"
info "Log file: ${LOG_FILE}"
else
error "Script execution failed with exit code: ${exit_code}"
error "Check log file for details: ${LOG_FILE}"
fi
show_elapsed_time
# Restore original file descriptors
exec 1>&3 2>&4 3>&- 4>&-
}
#######################################
# Initialize logging system and create necessary directories
#
# This function sets up the logging system according to XDG base directory
# specification. It creates required directories, manages log rotation,
# and initializes log files with system information.
#
# Globals:
# APP_LOG_DIR
# APP_CACHE_DIR
# XDG_CONFIG_HOME
# LOG_FILE
#
# Arguments:
# None
#
# Returns:
# 0 on success, non-zero on failure
#
# Example:
# setup_logging
# echo "Logging initialized to $LOG_FILE"
#######################################
setup_logging() {
# Create necessary directories
mkdir -p "${APP_LOG_DIR}" "${APP_CACHE_DIR}" "${XDG_CONFIG_HOME}/${APP_NAME}"
# Set up log rotation (keep last 5 logs)
if [[ -d "${APP_LOG_DIR}" ]]; then
# List all log files sorted by time (newest first)
local old_logs
if is_macos; then
old_logs=$(find "${APP_LOG_DIR}" -name "setup_*.log" -exec stat -f "%m %N" {} \; | sort -rn | tail -n +6 | cut -d' ' -f2-)
else
old_logs=$(find "${APP_LOG_DIR}" -name "setup_*.log" -printf "%T@ %p\n" | sort -rn | tail -n +6 | cut -d' ' -f2-)
fi
# Remove old logs if they exist
if [[ -n "${old_logs}" ]]; then
echo "${old_logs}" | xargs rm -f
fi
fi
# Save original file descriptors
exec 3>&1 4>&2
# Redirect stdout and stderr to both console and log file
exec 1> >(tee -a "${LOG_FILE}") 2>&1
# Log initial information
info "Started logging to ${LOG_FILE}"
info "Script version: ${SCRIPT_VERSION}"
info "OS type: $(uname -s)"
info "Shell: ${SHELL}"
info "User: ${USER}"
info "Home: ${HOME}"
# Log system information
if is_macos; then
info "macOS version: $(sw_vers -productVersion)"
else
info "Linux distribution: $(lsb_release -ds 2>/dev/null || cat /etc/os-release | grep PRETTY_NAME | cut -d= -f2)"
fi
}
#######################################
# Create default configuration file
# Arguments:
# None
#######################################
create_default_config() {
if [[ -f "${CONFIG_FILE}" ]]; then
debug_log "Configuration file already exists: ${CONFIG_FILE}"
return 0
fi
cat > "${CONFIG_FILE}" <<EOF
# Setup configuration file
# Created on: $(date)
# Version: ${SCRIPT_VERSION}
# Debug and logging
DEBUG_ENABLE=0
VERBOSE=0
# Installation behavior
DRY_RUN=0
FORCE_INSTALL=0
# Proxy settings
PROXY_ENABLED=0
PROXY_URL="http://127.0.0.1:7890"
# Component selection
INSTALL_BASIC=true
INSTALL_GUI=false
INSTALL_WAYLAND=false
INSTALL_PROGRAMMING=false
INSTALL_CHROMIUM_DEV=false
INSTALL_DOOM=false
INSTALL_VIM=true
INSTALL_CONFIGS=true
# Programming languages
INSTALL_PYTHON=false
INSTALL_NODE=false
INSTALL_GO=false
INSTALL_RUST=false
INSTALL_C=false
EOF
info "Created default configuration file: ${CONFIG_FILE}"
}
#######################################
# Load configuration from file
# Arguments:
# None
#######################################
load_config() {
if [[ ! -f "${CONFIG_FILE}" ]]; then
debug_log "No configuration file found, creating default"
create_default_config
fi
debug_log "Loading configuration from ${CONFIG_FILE}"
# shellcheck source=/dev/null
source "${CONFIG_FILE}"
}
#######################################
# Check system resources
# Arguments:
# None
#######################################
check_system_resources() {
local min_memory=2048 # 2GB in MB
local min_disk=5120 # 5GB in MB
# Check memory
local total_memory
if is_macos; then
# Get memory in MB on macOS
total_memory=$(sysctl -n hw.memsize | awk '{print $1/1024/1024}')
else
# Get memory in MB on Linux
total_memory=$(awk '/MemTotal/ {print $2/1024}' /proc/meminfo)
fi
if [[ -n "$total_memory" ]] && (( ${total_memory%.*} < min_memory )); then
warn "Low memory: ${total_memory%.*}MB available, ${min_memory}MB recommended"
fi
# Check disk space
local available_space
if is_macos; then
available_space=$(df -m "${HOME}" | awk 'NR==2 {print $4}')
else
available_space=$(df -m "${HOME}" | awk 'NR==2 {print $4}')
fi
if [[ -n "$available_space" ]] && (( available_space < min_disk )); then
warn "Low disk space: ${available_space}MB available, ${min_disk}MB recommended"
fi
debug_log "System resources check completed"
}
#######################################
# Check network connectivity
# Arguments:
# None
#######################################
check_network() {
local test_urls=(
"https://github.com"
"https://www.google.com"
)
for url in "${test_urls[@]}"; do
if ! curl --silent --head --fail "$url" >/dev/null; then
warn "Unable to reach ${url}"
if [[ "$url" == "https://github.com" ]]; then
warn "GitHub is not accessible, some features may not work"
prompt_proxy_setup
fi
fi
done
debug_log "Network connectivity check completed"
}
#######################################
# Check if a command exists
# Arguments:
# Command name
# Returns:
# 0 if command exists, 1 otherwise
#######################################
is_executable() {
command -v "$1" &>/dev/null
}
#######################################
# Check for required dependencies
# Arguments:
# None
#######################################
check_dependencies() {
local missing_deps=()
local required_cmds=(
git curl wget sudo
)
for cmd in "${required_cmds[@]}"; do
if ! is_executable "$cmd"; then
missing_deps+=("$cmd")
fi
done
if [[ ${#missing_deps[@]} -ne 0 ]]; then
error "Missing required dependencies: ${missing_deps[*]}"
info "Please install the missing dependencies and try again"
exit 1
fi
debug_log "Dependency check completed"
}
#######################################
# Backup existing configurations
# Arguments:
# None
#######################################
backup_configs() {
local files_to_backup=(
"${HOME}/.zshrc"
"${HOME}/.vimrc"
"${HOME}/.tmux.conf"
"${HOME}/.gitconfig"
"${CONFIG_HOME}/nvim"
)
info "Creating backup of existing configurations..."
mkdir -p "${BACKUP_DIR}"
for file in "${files_to_backup[@]}"; do
if [[ -e "${file}" ]]; then
cp -rp "${file}" "${BACKUP_DIR}/"
info "Backed up ${file} to ${BACKUP_DIR}/$(basename "${file}")"
fi
done
}
#######################################
# Install configuration files from configs directory
# Arguments:
# $1 - Optional: specific config to install (e.g., "vim")
#######################################
install_configs() {
# Use parameter expansion with default empty string to avoid unbound variable
local specific_config="${1:-}"
local configs_dir="${SCRIPT_DIR}/configs"
# Directory-based configs (using symlinks)
local config_dirs=(
"alacritty:${CONFIG_HOME}/alacritty"
"ctags:${CONFIG_HOME}/ctags"
"foot:${CONFIG_HOME}/foot"
"gdb:${CONFIG_HOME}/gdb"
"rofi:${CONFIG_HOME}/rofi"
"sway:${CONFIG_HOME}/sway"
"vim:${CONFIG_HOME}/vim"
"zsh:${CONFIG_HOME}/zsh"
)
# Single file configs (using individual symlinks)
local config_files=(
"tmux:${SCRIPT_DIR}/tmux.conf:${HOME}/.tmux.conf"
"zsh:${configs_dir}/zsh/zshrc.zsh:${HOME}/.zshrc"
)
# Special handling for vim config
if [[ -d "${configs_dir}/vim" ]] && { [[ -z "${specific_config}" ]] || [[ "${specific_config}" == "vim" ]]; }; then
# Create vim-dev directory and install vim-plug
info "Installing vim-plug..."
mkdir -p "${HOME}/vim-dev"
if ! git clone https://github.com/junegunn/vim-plug.git "${HOME}/vim-dev/plug.nvim" 2>/dev/null; then
if [[ ! -d "${HOME}/vim-dev/plug.nvim" ]]; then
warning "Failed to install vim-plug"
else
info "vim-plug already installed"
fi
else
info "vim-plug installed successfully"
fi
# Link vimrc
info "Linking vimrc..."
ln -sf "${configs_dir}/vim/vimrc" "${HOME}/.vimrc"
fi
info "Installing configuration files..."
# Create required parent directories
mkdir -p "${CONFIG_HOME}"
# Process each configuration directory
for config_pair in "${config_dirs[@]}"; do
local config_name="${config_pair%%:*}"
local src_dir="${configs_dir}/${config_name}"
local dest_dir="${config_pair#*:}"
# Skip if specific config is requested and this isn't it
if [[ -n "${specific_config}" ]] && [[ "${config_name}" != "${specific_config}" ]]; then
continue
fi
if [[ -d "${src_dir}" ]]; then
# Backup existing config if it exists and isn't a symlink
if [[ -d "${dest_dir}" && ! -L "${dest_dir}" ]]; then
cp -rp "${dest_dir}" "${BACKUP_DIR}/"
info "Backed up ${dest_dir} to ${BACKUP_DIR}/$(basename "${dest_dir}")"
rm -rf "${dest_dir}"
fi
# Remove existing symlink if it exists
[[ -L "${dest_dir}" ]] && rm "${dest_dir}"
# Create parent directory if it doesn't exist
mkdir -p "$(dirname "${dest_dir}")"
# Create symlink
ln -sf "${src_dir}" "${dest_dir}"
info "Linked ${src_dir} to ${dest_dir}"
else
warning "Config directory ${src_dir} not found"
fi
done
# Process each single configuration file
for config_pair in "${config_files[@]}"; do
# 解析三段式字符串 "类型:源文件:目标文件"
local config_type="${config_pair%%:*}"
local remaining="${config_pair#*:}"
local src_file="${remaining%%:*}"
local dest_file="${remaining#*:}"
# 检查特定配置是否被请求
if [[ -n "${specific_config}" ]] && [[ "${config_type}" != "${specific_config}" ]]; then
continue
fi
if [[ -f "${src_file}" ]]; then
# Backup existing config if it exists and isn't a symlink
if [[ -f "${dest_file}" && ! -L "${dest_file}" ]]; then
cp -p "${dest_file}" "${BACKUP_DIR}/"
info "Backed up ${dest_file} to ${BACKUP_DIR}/$(basename "${dest_file}")"
fi
# Remove existing file or symlink
[[ -e "${dest_file}" ]] && rm "${dest_file}"
# Create parent directory if it doesn't exist
mkdir -p "$(dirname "${dest_file}")"
# Create symlink
ln -sf "${src_file}" "${dest_file}"
info "Linked ${src_file} to ${dest_file}"
else
warning "Config file ${src_file} not found"
fi
done
# Install vim plugins if vim config and vim-plug are present
if [[ -d "${configs_dir}/vim" ]] && [[ -d "${HOME}/vim-dev/plug.nvim" ]] && [[ "${DRY_RUN}" != "1" ]]; then
info "Installing vim plugins..."
if [[ -x "$(command -v vim)" ]]; then
if ! vim +PlugInstall +qall; then
warning "Failed to install vim plugins"
else
info "vim plugins installed successfully"
fi
else
warning "vim not found, skipping plugin installation"
fi
fi
# Special handling for zsh: Install oh-my-zsh and plugins if needed
if [[ -d "${configs_dir}/zsh" ]] && { [[ -z "${specific_config}" ]] || [[ "${specific_config}" == "zsh" ]]; }; then
if [[ ! -d "${OHMYZSH_HOME}" ]]; then
info "Installing Oh My Zsh..."
if ! git clone --depth=1 "${REPO_OHMYZSH}" "${OHMYZSH_HOME}" 2>/dev/null; then
if [[ ! -d "${OHMYZSH_HOME}" ]]; then
warning "Failed to install Oh My Zsh"
else
info "Oh My Zsh already installed"
fi
else
info "Oh My Zsh installed successfully"
fi
fi
# Install custom plugins
if [[ -d "${OHMYZSH_HOME}" ]]; then
# Install Powerlevel10k theme
if [[ ! -d "${ZSH_CUSTOM}/themes/powerlevel10k" ]]; then
info "Installing Powerlevel10k theme..."
git clone --depth=1 "${REPO_P10K}" "${ZSH_CUSTOM}/themes/powerlevel10k"
fi
# Install zsh-autosuggestions
if [[ ! -d "${ZSH_CUSTOM}/plugins/zsh-autosuggestions" ]]; then
info "Installing zsh-autosuggestions..."
git clone --depth=1 "${REPO_ZSH_SUGGESTION}" "${ZSH_CUSTOM}/plugins/zsh-autosuggestions"
fi
fi
fi
info "Configuration files installation completed"
}
#######################################
# Check if running on macOS
# Returns:
# 0 if macOS, 1 otherwise
#######################################
is_macos() {
[[ "$OSTYPE" == "darwin"* ]]
}
#######################################
# Check if running on Ubuntu
# Returns:
# 0 if Ubuntu, 1 otherwise
#######################################
is_ubuntu() {
[[ "$(lsb_release -is 2>/dev/null)" =~ "Ubuntu" ]]
}
#######################################
# Check if running on Arch Linux
# Returns:
# 0 if Arch, 1 otherwise
#######################################
is_arch() {
[[ "$(lsb_release -is 2>/dev/null)" =~ "Arch" ]]
}
#######################################
# Get system architecture
# Returns:
# Architecture string (386, amd64, arm, arm64)
#######################################
get_arch() {
local architecture=""
case $(uname -m) in
i386) architecture="386" ;;
i686) architecture="386" ;;
x86_64) architecture="amd64" ;;
arm) dpkg --print-architecture 2>/dev/null | grep -q "arm64" &&
architecture="arm64" || architecture="arm" ;;
esac
echo "$architecture"
}
#######################################
# Show progress bar
# Arguments:
# Current progress
# Total steps
# Optional description
#######################################
show_progress() {
local current=$1
local total=$2
local desc=${3:-"Progress"}
local width=50
local percentage=$((current * 100 / total))
local completed=$((width * current / total))
local remaining=$((width - completed))
printf "\r%s: [%${completed}s%${remaining}s] %d%%" \
"$desc" \
"$(printf '#%.0s' $(seq 1 $completed))" \
"$(printf ' %.0s' $(seq 1 $remaining))" \
"$percentage"
[[ $current -eq $total ]] && echo
}
#######################################
# Prompt for proxy setup
# Arguments:
# None
#######################################
prompt_proxy_setup() {
if [[ "${PROXY_ENABLED}" != "1" ]]; then
local response
read -rp "Would you like to configure a proxy? (y/N) " response
if [[ "${response}" =~ ^[Yy]$ ]]; then
read -rp "Enter proxy URL [${PROXY_URL}]: " input_url
PROXY_URL="${input_url:-${PROXY_URL}}"
PROXY_ENABLED=1
export http_proxy="${PROXY_URL}"
export https_proxy="${PROXY_URL}"
export HTTP_PROXY="${PROXY_URL}"
export HTTPS_PROXY="${PROXY_URL}"
info "Proxy configured: ${PROXY_URL}"
fi
fi
}
#######################################
# Install Homebrew if not present (macOS only)
# Arguments:
# None
# Returns:
# 0 on success, 1 on failure
#######################################
ensure_homebrew() {
if ! is_macos; then
return 0
fi
if ! is_executable brew; then
info "Installing Homebrew..."
if [[ "${DRY_RUN}" != "1" ]]; then
# Download and verify the install script
local install_script
install_script="$(mktemp)"
curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh > "$install_script"