-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup
More file actions
executable file
·1265 lines (1090 loc) · 37.5 KB
/
setup
File metadata and controls
executable file
·1265 lines (1090 loc) · 37.5 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
#
# Configure a macOS development environment from this dotfiles repository.
# The script supports modular execution, dry runs, and first-level symlink
# management for both config/ and link/.
set -euo pipefail
SCRIPT_NAME="$(basename "$0")"
readonly SCRIPT_NAME
readonly DOTFILES_DIR="$HOME/.dotfiles"
readonly CONFIG_PATH="$HOME/.config"
readonly BREW_PREFIX="/opt/homebrew"
readonly COLOR_TIMESTAMP='\033[0;36m'
readonly COLOR_INFO='\033[0;32m'
readonly COLOR_WARNING='\033[0;33m'
readonly COLOR_ERROR='\033[0;31m'
readonly COLOR_STATUS='\033[0;35m'
readonly COLOR_MAIN='\033[0;34m'
readonly COLOR_TASK='\033[0;36m'
readonly COLOR_CMD='\033[1;36m'
readonly COLOR_ARG='\033[1;33m'
readonly COLOR_PATH='\033[1;34m'
readonly COLOR_ARROW='\033[1;37m'
readonly COLOR_GREEN='\033[1;32m'
readonly COLOR_RESET='\033[0m'
readonly INDENT_LVL0=""
readonly INDENT_LVL1=" "
readonly INDENT_LVL2=" "
readonly INDENT_LVL3=" "
readonly DEFAULTS_FIELD_SEPARATOR=$'\t'
readonly GIT_CONFIG_FIELD_SEPARATOR=$'\t'
readonly STARTUP_SOUND_DISABLED_VALUE='%80'
DRY_RUN=false
VERBOSE=false
EXPLICIT_MODULES_SELECTED=false
MODULE_SYSTEM=true
MODULE_CONFIG=true
MODULE_BREW=true
MODULE_SHELL=true
MODULE_GIT=true
MODULE_TOOLS=true
readonly -a SYSTEM_DEFAULTS=(
$'-g\t_HIHideMenuBar\t-bool\ttrue'
$'-g\tAppleKeyboardUIMode\t-int\t2'
$'-g\tApplePressAndHoldEnabled\t-bool\tfalse'
$'-g\tInitialKeyRepeat\t-int\t10'
$'-g\tKeyRepeat\t-int\t1'
$'com.apple.HIToolbox\tAppleDictationAutoEnable\t-int\t0'
$'com.apple.HIToolbox\tAppleFnUsageType\t-int\t0'
$'-g\tAppleIconAppearanceTheme\t-string\tRegularDark'
$'-g\tNSGlassDiffusionSetting\t-int\t1'
$'-g\tAppleShowScrollBars\t-string\tWhenScrolling'
$'-g\tAppleScrollerPagingBehavior\t-bool\ttrue'
$'-g\tcom.apple.keyboard.fnState\t-bool\ttrue'
$'-g\tcom.apple.swipescrolldirection\t-bool\ttrue'
$'-g\tNSAutomaticDashSubstitutionEnabled\t-bool\tfalse'
$'-g\tNSAutomaticPeriodSubstitutionEnabled\t-bool\tfalse'
$'-g\tNSAutomaticQuoteSubstitutionEnabled\t-bool\tfalse'
$'-g\tNSAutomaticCapitalizationEnabled\t-bool\tfalse'
$'-g\tNSNavPanelExpandedStateForSaveMode\t-bool\ttrue'
$'-g\tNSNavPanelExpandedStateForSaveMode2\t-bool\ttrue'
$'-g\tNSDocumentSaveNewDocumentsToCloud\t-bool\tfalse'
$'-g\tAppleWindowTabbingMode\t-string\talways'
$'-g\tNSToolbarTitleViewRolloverDelay\t-int\t0'
$'com.apple.dock\ttilesize\t-int\t48'
$'com.apple.dock\torientation\t-string\tbottom'
$'com.apple.dock\tautohide\t-bool\ttrue'
$'com.apple.dock\tmru-spaces\t-bool\tfalse'
$'com.apple.dock\tshow-recents\t-bool\tfalse'
$'com.apple.dock\tshow-process-indicators\t-bool\tfalse'
$'com.apple.finder\tQuitMenuItem\t-bool\ttrue'
$'com.apple.finder\tFXEnableExtensionChangeWarning\t-bool\tfalse'
$'com.apple.finder\tAppleShowAllExtensions\t-bool\ttrue'
$'com.apple.finder\tAppleShowAllFiles\t-bool\ttrue'
$'com.apple.finder\tFXPreferredViewStyle\t-string\tclmv'
$'com.apple.finder\tFXDefaultSearchScope\t-string\tSCcf'
$'com.apple.finder\tShowHardDrivesOnDesktop\t-bool\tfalse'
$'com.apple.finder\tShowRemovableMediaOnDesktop\t-bool\tfalse'
$'com.apple.finder\tShowExternalHardDrivesOnDesktop\t-bool\tfalse'
$'com.apple.finder\tShowMountedServersOnDesktop\t-bool\tfalse'
$'com.apple.finder\tShowRecentTags\t-bool\tfalse'
$'com.apple.finder\tNewWindowTarget\t-string\tPfHm'
$'com.apple.finder\tNewWindowTargetPath\t-string\t'"file://$HOME/"
$'com.apple.finder\tQLEnableTextSelection\t-bool\ttrue'
$'com.apple.WindowManager\tHideDesktop\t-bool\ttrue'
$'com.apple.WindowManager\tStandardHideDesktopIcons\t-bool\ttrue'
$'com.apple.WindowManager\tEnableStandardClickToShowDesktop\t-bool\tfalse'
$'com.apple.WindowManager\tAutoHide\t-bool\ttrue'
$'com.apple.WindowManager\tStandardHideWidgets\t-bool\ttrue'
$'com.apple.WindowManager\tStageManagerHideWidgets\t-bool\ttrue'
$'com.apple.AppleMultitouchTrackpad\tClicking\t-bool\ttrue'
$'com.apple.AppleMultitouchTrackpad\tTrackpadRightClick\t-bool\ttrue'
$'com.apple.AppleMultitouchTrackpad\tTrackpadThreeFingerTapGesture\t-int\t0'
$'com.apple.driver.AppleBluetoothMultitouch.trackpad\tClicking\t-bool\ttrue'
$'com.apple.driver.AppleBluetoothMultitouch.trackpad\tTrackpadRightClick\t-bool\ttrue'
$'com.apple.driver.AppleBluetoothMultitouch.trackpad\tTrackpadThreeFingerTapGesture\t-int\t0'
$'-g\tcom.apple.trackpad.forceClick\t-bool\tfalse'
$'-g\tcom.apple.trackpad.scaling\t-float\t1.5'
$'-g\tshouldShowRSVPDataDetectors\t-bool\tfalse'
$'com.apple.LaunchServices\tLSQuarantine\t-bool\tfalse'
$'com.apple.desktopservices\tDSDontWriteUSBStores\t-bool\ttrue'
$'com.apple.desktopservices\tDSDontWriteNetworkStores\t-bool\ttrue'
$'com.apple.CrashReporter\tDialogType\t-string\tnone'
$'com.apple.frameworks.diskimages\tskip-verify\t-bool\ttrue'
$'com.apple.frameworks.diskimages\tskip-verify-locked\t-bool\ttrue'
$'com.apple.frameworks.diskimages\tskip-verify-remote\t-bool\ttrue'
$'com.apple.AdLib\tforceLimitAdTracking\t-bool\ttrue'
$'com.apple.AdLib\tallowApplePersonalizedAdvertising\t-bool\tfalse'
$'com.apple.AdLib\tallowIdentifierForAdvertising\t-bool\tfalse'
)
# Control Center module display modes mirror the current values returned by
# `defaults -currentHost read com.apple.controlcenter` on this machine.
readonly -a CURRENT_HOST_SYSTEM_DEFAULTS=(
$'com.apple.controlcenter\tAirDrop\t-int\t8'
$'com.apple.controlcenter\tBattery\t-int\t4'
$'com.apple.controlcenter\tBluetooth\t-int\t24'
$'com.apple.controlcenter\tFocusModes\t-int\t8'
$'com.apple.controlcenter\tKeyboardBrightness\t-int\t8'
$'com.apple.controlcenter\tSpotlight\t-int\t8'
$'com.apple.controlcenter\tTimer\t-int\t2'
$'com.apple.controlcenter\tVoiceControl\t-int\t8'
$'com.apple.controlcenter\tWeather\t-int\t8'
$'com.apple.controlcenter\tWiFi\t-int\t24'
)
readonly -a PMSET_SETTINGS=(
$'-b\tlowpowermode\t0'
$'-b\tlessbright\t0'
$'-b\tdisplaysleep\t5'
)
readonly -a GIT_CONFIG_SETTINGS=(
$'core.editor\tnvim'
$'core.excludesFile\t'"$HOME/.gitignore_global"
$'core.attributesFile\t'"$HOME/.gitattributes_global"
$'init.defaultbranch\tmain'
$'pull.rebase\ttrue'
$'push.autoSetupRemote\ttrue'
$'merge.conflictStyle\tzdiff3'
$'fetch.writeCommitGraph\ttrue'
$'rerere.enabled\ttrue'
$'column.ui\tauto'
$'branch.sort\t-committerdate'
$'gpg.format\tssh'
$'user.signingKey\t'"$HOME/.ssh/key.pub"
$'commit.gpgsign\ttrue'
$'maintenance.auto\tfalse'
$'maintenance.strategy\tincremental'
$'diff.colormoved\tdefault'
$'diff.nodiff.command\ttrue'
$'diff.nodiff.binary\ttrue'
$'diff.tool\tdifftastic'
$'diff.external\tdifft --color=always'
$'difftool.prompt\tfalse'
$'difftool.difftastic.cmd\tdifft "$LOCAL" "$REMOTE"'
$'pager.difftool\ttrue'
$'core.pager\tdelta'
$'interactive.difffilter\tdelta --color-only'
$'delta.light\tfalse'
$'delta.navigate\ttrue'
$'delta.side-by-side\ttrue'
$'delta.line-numbers\ttrue'
$'delta.syntax-theme\tDracula'
)
log_info() {
printf '%b\n' \
"${COLOR_TIMESTAMP}[$(date +'%Y-%m-%d %H:%M:%S')]${COLOR_RESET} ${COLOR_INFO}INFO${COLOR_RESET} $*"
}
log_warn() {
printf '%b\n' \
"${COLOR_TIMESTAMP}[$(date +'%Y-%m-%d %H:%M:%S')]${COLOR_RESET} ${COLOR_WARNING}⚠️ ${COLOR_RESET} $*"
}
log_error() {
printf '%b\n' \
"${COLOR_TIMESTAMP}[$(date +'%Y-%m-%d %H:%M:%S')]${COLOR_RESET} ${COLOR_ERROR}❌${COLOR_RESET} $*" \
>&2
exit 1
}
log_main() {
printf '%b\n' \
"${COLOR_TIMESTAMP}[$(date +'%Y-%m-%d %H:%M:%S')]${COLOR_RESET} ${COLOR_MAIN}⚙️ ${COLOR_RESET} ${INDENT_LVL0}$*"
}
log_task() {
printf '%b\n' \
"${COLOR_TIMESTAMP}[$(date +'%Y-%m-%d %H:%M:%S')]${COLOR_RESET} ${COLOR_TASK}📋${COLOR_RESET} ${INDENT_LVL1}$*"
}
log_subtask() {
printf '%b\n' \
"${COLOR_TIMESTAMP}[$(date +'%Y-%m-%d %H:%M:%S')]${COLOR_RESET} ${COLOR_TASK}📝${COLOR_RESET} ${INDENT_LVL2}$*"
}
log_status() {
printf '%b\n' \
"${COLOR_TIMESTAMP}[$(date +'%Y-%m-%d %H:%M:%S')]${COLOR_RESET} ${COLOR_STATUS}✅${COLOR_RESET} ${INDENT_LVL3}$*"
}
log_preview() {
printf '%b\n' \
"${COLOR_TIMESTAMP}[$(date +'%Y-%m-%d %H:%M:%S')]${COLOR_RESET} ${COLOR_STATUS}PREVIEW${COLOR_RESET} ${INDENT_LVL2}$*"
}
log_manual_confirmation_section() {
local section_title="$1"
shift
local step=""
local step_number=1
log_task "$section_title"
for step in "$@"; do
log_subtask "${step_number}. ${step}"
step_number=$((step_number + 1))
done
}
count_first_level_items() {
local source_dir="$1"
find "$source_dir" -mindepth 1 -maxdepth 1 | wc -l | tr -d '[:space:]'
}
count_brewfile_entries() {
local brewfile_path="$1"
local entry_type="$2"
awk -v entry_type="$entry_type" '
$0 ~ "^[[:space:]]*" entry_type "[[:space:]]+\"" { count++ }
END { print count + 0 }
' "$brewfile_path"
}
preview_brewfile_entries() {
local brewfile_path="$1"
local entry_type=""
local entry_name=""
local entry_label=""
while IFS=$'\t' read -r entry_type entry_name; do
if [[ -z "$entry_type" || -z "$entry_name" ]]; then
continue
fi
if [[ "$entry_type" == "brew" ]]; then
entry_label="formula"
else
entry_label="cask"
fi
log_preview "Would install ${entry_label}: ${COLOR_PATH}${entry_name}${COLOR_RESET}"
done < <(
awk '
/^[[:space:]]*(brew|cask)[[:space:]]+"/ {
line = $0
sub(/^[[:space:]]*/, "", line)
entry_type = line
sub(/[[:space:]].*$/, "", entry_type)
sub(/^[[:space:]]*(brew|cask)[[:space:]]+"/, "", line)
sub(/".*$/, "", line)
printf "%s\t%s\n", entry_type, line
}
' "$brewfile_path"
)
}
render_command() {
local rendered_command=""
local arg=""
local escaped_arg=""
for arg in "$@"; do
printf -v escaped_arg '%q' "$arg"
rendered_command+="${rendered_command:+ }${escaped_arg}"
done
printf '%s\n' "$rendered_command"
}
execute_with_log() {
local cmd="$1"
shift
local -a args=("$@")
local rendered_command=""
if (( ${#args[@]} > 0 )); then
rendered_command="$(render_command "$cmd" "${args[@]}")"
else
rendered_command="$(render_command "$cmd")"
fi
if [[ "$DRY_RUN" != "true" ]]; then
log_task "EXECUTING: ${COLOR_CMD}${rendered_command}${COLOR_RESET}"
if (( ${#args[@]} > 0 )); then
"$cmd" "${args[@]}"
else
"$cmd"
fi
else
log_preview "Would execute: ${COLOR_CMD}${rendered_command}${COLOR_RESET}"
fi
}
#######################################
# Write a single macOS defaults entry.
# Arguments:
# $1: Domain
# $2: Key
# $3: Flag such as -bool, -int, or -string
# $4: Value
#######################################
write_default_setting() {
local domain="$1"
local key="$2"
local flag="$3"
local value="$4"
execute_with_log defaults write "${domain}" "${key}" "${flag}" "${value}"
}
#######################################
# Apply a list of "domain key flag value" defaults entries.
# Arguments:
# Array entries as positional parameters
#######################################
apply_defaults_entries() {
local entry=""
local domain=""
local key=""
local flag=""
local value=""
for entry in "$@"; do
IFS="${DEFAULTS_FIELD_SEPARATOR}" read -r domain key flag value <<<"${entry}"
write_default_setting "${domain}" "${key}" "${flag}" "${value}"
done
}
#######################################
# Write a single macOS defaults entry in the current host domain.
# Arguments:
# $1: Domain
# $2: Key
# $3: Flag such as -bool, -int, or -string
# $4: Value
#######################################
write_current_host_default_setting() {
local domain="$1"
local key="$2"
local flag="$3"
local value="$4"
execute_with_log defaults -currentHost write "${domain}" "${key}" "${flag}" "${value}"
}
#######################################
# Apply a list of current-host "domain key flag value" defaults entries.
# Globals:
# DEFAULTS_FIELD_SEPARATOR
# Arguments:
# Array entries as positional parameters
#######################################
apply_current_host_defaults_entries() {
local entry=""
local domain=""
local key=""
local flag=""
local value=""
for entry in "$@"; do
IFS="${DEFAULTS_FIELD_SEPARATOR}" read -r domain key flag value <<<"${entry}"
write_current_host_default_setting "${domain}" "${key}" "${flag}" "${value}"
done
}
#######################################
# Clear all persistent Dock apps while keeping folder stacks untouched.
#######################################
clear_dock_persistent_apps() {
execute_with_log defaults write com.apple.dock persistent-apps -array
}
#######################################
# Restart a UI process only when it is currently running.
# Arguments:
# $1: Process name
#######################################
refresh_ui_process_if_running() {
local process_name="$1"
if pgrep -x "${process_name}" >/dev/null 2>&1; then
execute_with_log killall "${process_name}"
fi
}
#######################################
# Check whether the current machine has an internal battery.
# Returns:
# 0 if an internal battery is present, non-zero otherwise
#######################################
pmset_has_internal_battery() {
pmset -g batt | grep -Eq 'InternalBattery|Battery'
}
#######################################
# Check whether pmset supports a given setting for the requested scope.
# Arguments:
# $1: pmset scope such as -b or -a
# $2: pmset setting name
#######################################
pmset_supports_setting() {
local scope="$1"
local setting="$2"
if pmset -g cap | grep -Eq "(^|[[:space:]])${setting}($|[[:space:]])"; then
return 0
fi
if [[ "${scope}" == "-b" ]] && pmset_has_internal_battery; then
case "${setting}" in
displaysleep | lessbright)
return 0
;;
esac
fi
return 1
}
#######################################
# Apply a list of pmset scope/key/value entries.
# Globals:
# DEFAULTS_FIELD_SEPARATOR
# Arguments:
# Array entries as positional parameters
#######################################
apply_pmset_entries() {
local entry=""
local scope=""
local setting=""
local value=""
for entry in "$@"; do
IFS="${DEFAULTS_FIELD_SEPARATOR}" read -r scope setting value <<<"${entry}"
if pmset_supports_setting "${scope}" "${setting}"; then
execute_with_log sudo pmset "${scope}" "${setting}" "${value}"
else
log_warn "Skipping unsupported power setting: ${setting}"
fi
done
}
#######################################
# Configure screen lock to require the password immediately.
#######################################
screen_lock_is_immediate() {
local screen_lock_status=""
screen_lock_status="$(sysadminctl -screenLock status 2>&1 || true)"
[[ "${screen_lock_status}" == *"screenLock delay is immediate"* ]]
}
configure_screen_lock_settings() {
log_task "Configuring screen lock to require the password immediately..."
if screen_lock_is_immediate; then
log_subtask "Screen lock already requires the password immediately"
return
fi
execute_with_log sysadminctl -screenLock immediate -password -
}
#######################################
# Configure the first day of week to Monday.
#######################################
configure_first_day_of_week() {
log_task "Configuring the first day of week to Monday..."
execute_with_log defaults write NSGlobalDomain AppleFirstWeekday -dict gregorian 2
}
#######################################
# Check whether startup sound is already disabled.
# Returns:
# 0 if disabled, non-zero otherwise
#######################################
startup_sound_is_disabled() {
local current_value=""
current_value="$(nvram SystemAudioVolume 2>/dev/null | awk '{print $2}' || true)"
[[ "${current_value}" == "${STARTUP_SOUND_DISABLED_VALUE}" ]]
}
#######################################
# Disable the startup sound.
#######################################
configure_startup_sound() {
log_task "Disabling startup sound..."
if startup_sound_is_disabled; then
log_subtask "Startup sound already disabled"
return
fi
execute_with_log sudo nvram "SystemAudioVolume=${STARTUP_SOUND_DISABLED_VALUE}"
}
#######################################
# Apply a list of Git global config key/value pairs.
# Globals:
# GIT_CONFIG_FIELD_SEPARATOR
# Arguments:
# Array entries as positional parameters
#######################################
apply_git_config_entries() {
local entry=""
local key=""
local value=""
for entry in "$@"; do
IFS="${GIT_CONFIG_FIELD_SEPARATOR}" read -r key value <<<"${entry}"
execute_with_log git config --global "${key}" "${value}"
done
}
show_help() {
cat <<EOF
Usage: ${SCRIPT_NAME} [OPTIONS]
Initialize macOS development environment with configurable modules.
Options:
--dry-run Run without making changes (for testing)
--verbose Enable verbose output
--modules List available modules
--system Configure macOS system defaults
--config Link configuration files
--brew Install applications via Homebrew
--shell Configure shell (fish)
--git Configure Git
--tools Initialize developer tooling (Neovim, tmux, Rust, JS)
--help Show this help message
Examples:
${SCRIPT_NAME} # Run all modules (default)
${SCRIPT_NAME} --brew --shell # Run only Homebrew and shell modules
${SCRIPT_NAME} --dry-run --git # Dry run for Git configuration only
EOF
}
list_modules() {
cat <<'EOF'
Available modules:
--system : macOS system defaults
--config : Config linking
--brew : Homebrew and applications
--shell : Shell configuration (fish)
--git : Git configuration
--tools : Developer tooling (Neovim, tmux, Rust, JS)
EOF
}
disable_all_modules() {
MODULE_SYSTEM=false
MODULE_CONFIG=false
MODULE_BREW=false
MODULE_SHELL=false
MODULE_GIT=false
MODULE_TOOLS=false
}
mark_explicit_module_selection() {
if [[ "$EXPLICIT_MODULES_SELECTED" == "true" ]]; then
return
fi
EXPLICIT_MODULES_SELECTED=true
disable_all_modules
}
enable_module() {
local module_name="$1"
mark_explicit_module_selection
case "$module_name" in
system) MODULE_SYSTEM=true ;;
config) MODULE_CONFIG=true ;;
brew) MODULE_BREW=true ;;
shell) MODULE_SHELL=true ;;
git) MODULE_GIT=true ;;
tools) MODULE_TOOLS=true ;;
*)
log_error "Unknown module: ${module_name}"
;;
esac
}
parse_args() {
local arg
while [[ $# -gt 0 ]]; do
arg="$1"
case "$arg" in
--help)
show_help
exit 0
;;
--modules)
list_modules
exit 0
;;
--dry-run)
DRY_RUN=true
;;
--verbose)
VERBOSE=true
;;
--system)
enable_module system
;;
--config)
enable_module config
;;
--brew)
enable_module brew
;;
--shell)
enable_module shell
;;
--git)
enable_module git
;;
--tools)
enable_module tools
;;
*)
printf 'Unknown option: %s\n' "$arg"
printf 'Use --help for usage information.\n'
exit 1
;;
esac
shift
done
}
enable_verbose_tracing() {
if [[ "$VERBOSE" == "true" && "$DRY_RUN" != "true" ]]; then
set -x
fi
}
log_execution_mode() {
if [[ "$DRY_RUN" == "true" && "$VERBOSE" == "true" ]]; then
log_task "Execution mode: DRY RUN with VERBOSE output - no changes will be made"
elif [[ "$DRY_RUN" == "true" ]]; then
log_task "Execution mode: DRY RUN - no changes will be made"
elif [[ "$VERBOSE" == "true" ]]; then
log_task "Execution mode: VERBOSE - detailed output will be shown"
else
log_task "Execution mode: NORMAL - standard output"
fi
enable_verbose_tracing
}
log_enabled_module() {
local module_name="$1"
local enabled="$2"
if [[ "$enabled" == "true" ]]; then
log_subtask "${module_name}: ${COLOR_GREEN}✅${COLOR_RESET}"
fi
}
log_enabled_modules() {
log_task "Enabled modules:"
log_enabled_module "macOS System Defaults" "$MODULE_SYSTEM"
log_enabled_module "Config Linking" "$MODULE_CONFIG"
log_enabled_module "Homebrew & Apps" "$MODULE_BREW"
log_enabled_module "Shell Configuration" "$MODULE_SHELL"
log_enabled_module "Git Configuration" "$MODULE_GIT"
log_enabled_module "Developer Tooling" "$MODULE_TOOLS"
}
should_authenticate_for_sudo() {
[[ "$DRY_RUN" != "true" ]] &&
[[ "$MODULE_SYSTEM" == "true" || "$MODULE_BREW" == "true" || \
"$MODULE_SHELL" == "true" ]]
}
keep_sudo_alive() {
while true; do
sleep 60
sudo -n true
kill -0 "$$" || exit
done 2>/dev/null &
}
authenticate_for_system_operations() {
if ! should_authenticate_for_sudo; then
return
fi
log_task "Authenticating for system operations (if needed)..."
if sudo -v; then
keep_sudo_alive
log_subtask "Authentication successful"
else
log_error "Failed to authenticate. Please run the script again and enter your password when prompted."
fi
}
ensure_xcode_command_line_tools() {
if [[ "$DRY_RUN" == "true" ]]; then
if xcode-select --print-path &>/dev/null; then
log_task "XCode Command Line Tools already installed"
else
log_preview "Would install XCode Command Line Tools"
fi
return
fi
if ! xcode-select --print-path &>/dev/null; then
log_task "Installing XCode Command Line Tools"
if xcode-select --install &>/dev/null; then
log_subtask "XCode Command Line Tools install initiated. Please follow the prompts."
else
log_warn "XCode Command Line Tools install failed to initiate"
fi
else
log_task "XCode Command Line Tools already installed"
fi
}
apply_system_defaults() {
if [[ "$DRY_RUN" == "true" && "$VERBOSE" != "true" ]]; then
log_task "Previewing macOS defaults changes..."
log_preview "Would apply ${#SYSTEM_DEFAULTS[@]} macOS defaults entries"
log_preview "Would apply ${#CURRENT_HOST_SYSTEM_DEFAULTS[@]} current-host Control Center entries"
log_preview "Would clear Dock persistent apps and apply ${#PMSET_SETTINGS[@]} power settings"
log_preview "Would configure first day of week, startup sound, and screen lock"
log_preview "Would refresh Dock, ControlCenter, and SystemUIServer when running"
log_preview "Use --dry-run --verbose to expand every macOS settings command"
return
fi
execute_with_log defaults write com.apple.finder FXInfoPanesExpanded -dict MetaData -bool true Preview -bool false
apply_defaults_entries "${SYSTEM_DEFAULTS[@]}"
apply_current_host_defaults_entries "${CURRENT_HOST_SYSTEM_DEFAULTS[@]}"
clear_dock_persistent_apps
apply_pmset_entries "${PMSET_SETTINGS[@]}"
configure_first_day_of_week
configure_startup_sound
configure_screen_lock_settings
execute_with_log killall Dock Finder
refresh_ui_process_if_running ControlCenter
refresh_ui_process_if_running SystemUIServer
}
run_system_module() {
if [[ "$MODULE_SYSTEM" != "true" ]]; then
log_main "Skipping macOS system defaults configuration (module disabled)"
return
fi
log_main "Installing XCode Command Line Tools if needed..."
ensure_xcode_command_line_tools
log_main "Configuring system settings..."
apply_system_defaults
}
run_homebrew_module() {
if [[ "$MODULE_BREW" != "true" ]]; then
log_main "Skipping Homebrew installation (module disabled)"
return
fi
log_main "Installing Homebrew if needed..."
if [[ "$DRY_RUN" == "true" ]]; then
if command -v brew >/dev/null 2>&1; then
log_task "Homebrew already installed"
else
log_preview "Would install Homebrew"
log_preview \
"Would execute: ${COLOR_CMD}/bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"${COLOR_RESET}"
fi
log_task "Homebrew PATH configuration handled via Fish configuration in config/fish/conf.d/path.fish"
return
fi
if ! command -v brew >/dev/null 2>&1; then
log_task "Installing Homebrew"
if ! /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"; then
log_error "Unable to install Homebrew, script abort!"
fi
else
log_task "Homebrew already installed"
fi
log_task "Homebrew PATH configuration handled via Fish configuration in config/fish/conf.d/path.fish"
}
remove_existing_target() {
local target_item="$1"
if [[ -e "$target_item" || -L "$target_item" ]]; then
log_subtask "Removing existing ${COLOR_PATH}${target_item}${COLOR_RESET}"
rm -rf "$target_item"
fi
}
symlink_first_level_items() {
local source_dir="$1"
local target_dir="$2"
local source_label="$3"
local should_create_target_dir="$4"
local item_count=""
local item=""
local item_name=""
local target_item=""
if [[ "$DRY_RUN" != "true" ]]; then
if [[ "$should_create_target_dir" == "true" ]]; then
mkdir -p "$target_dir"
fi
else
if [[ "$should_create_target_dir" == "true" ]]; then
log_preview "Would create directory: ${COLOR_PATH}${target_dir}${COLOR_RESET}"
fi
fi
if [[ "$DRY_RUN" == "true" && "$VERBOSE" != "true" ]]; then
item_count="$(count_first_level_items "$source_dir")"
log_preview \
"Would symlink ${item_count} item(s) from ${COLOR_PATH}${source_dir}${COLOR_RESET} to ${COLOR_PATH}${target_dir}${COLOR_RESET}"
return
fi
while IFS= read -r -d '' item; do
if [[ -e "$item" || -L "$item" ]]; then
item_name="$(basename "$item")"
target_item="${target_dir}/${item_name}"
if [[ "$DRY_RUN" != "true" ]]; then
remove_existing_target "$target_item"
log_task \
"Creating symlink: ${COLOR_PATH}${item}${COLOR_RESET} ${COLOR_ARROW}->${COLOR_RESET} ${COLOR_PATH}${target_item}${COLOR_RESET}"
execute_with_log ln -s "$item" "$target_item"
else
log_preview \
"Would symlink: ${COLOR_PATH}${item}${COLOR_RESET} ${COLOR_ARROW}->${COLOR_RESET} ${COLOR_PATH}${target_item}${COLOR_RESET}"
fi
else
log_warn "${source_label} source does not exist: ${COLOR_PATH}${item}${COLOR_RESET}"
fi
done < <(find "$source_dir" -mindepth 1 -maxdepth 1 -print0)
}
configure_ssh_settings() {
local ssh_config_path="$HOME/.ssh/config"
log_task "Configuring SSH settings..."
mkdir -p "$HOME/.ssh"
chmod 700 "$HOME/.ssh"
log_subtask "Creating SSH config: ${COLOR_PATH}${ssh_config_path}${COLOR_RESET}"
cat >>"$ssh_config_path" <<'EOF'
Host *
ServerAliveInterval 30
TCPKeepAlive yes
Compression yes
ServerAliveCountMax 6
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/key
EOF
log_subtask "Setting permissions for SSH config..."
chmod 600 "$ssh_config_path"
}
refresh_font_cache() {
log_task "Refreshing font cache..."
if command -v fc-cache >/dev/null 2>&1; then
execute_with_log fc-cache -f
else
log_warn "fc-cache command not found. Font cache refresh skipped."
fi
}
configure_login_settings() {
if [[ "$DRY_RUN" != "true" ]]; then
log_task "Creating ${COLOR_PATH}$HOME/.hushlogin${COLOR_RESET} to disable Last Login message"
execute_with_log touch "$HOME/.hushlogin"
configure_ssh_settings
refresh_font_cache
else
log_preview "Would touch: ${COLOR_PATH}$HOME/.hushlogin${COLOR_RESET}"
log_preview "Would create SSH directory and config with proper permissions"
log_preview "Would create SSH config: ${COLOR_PATH}$HOME/.ssh/config${COLOR_RESET}"
log_preview "Would execute: ${COLOR_CMD}fc-cache -f${COLOR_RESET}"
fi
}
run_config_module() {
if [[ "$MODULE_CONFIG" != "true" ]]; then
log_main "Skipping config linking (module disabled)"
return
fi
log_main "Creating config symlinks..."
symlink_first_level_items "$DOTFILES_DIR/config" "$CONFIG_PATH" "Config" "true"
log_main "Creating dotfile symlinks..."
symlink_first_level_items "$DOTFILES_DIR/link" "$HOME" "Link" "false"
log_main "Configuring login settings..."
configure_login_settings
}
eval_homebrew_shellenv() {
eval "$("${BREW_PREFIX}/bin/brew" shellenv)"
}
install_homebrew_packages() {
local brewfile_path="$DOTFILES_DIR/Brewfile"
local formula_count=""
local cask_count=""
if [[ "$MODULE_BREW" != "true" ]]; then
log_task "Skipping Homebrew packages installation (module disabled)"
return
fi
if [[ "$DRY_RUN" != "true" ]]; then
log_task "Updating environment to include Homebrew in PATH..."
eval_homebrew_shellenv
else
log_preview "Would update environment to include Homebrew in PATH"
fi
log_task "Installing Homebrew packages..."
log_subtask "Using Brewfile: ${COLOR_PATH}${brewfile_path}${COLOR_RESET}"
if [[ "$DRY_RUN" == "true" ]]; then
if [[ "$VERBOSE" == "true" ]]; then
preview_brewfile_entries "$brewfile_path"
else
formula_count="$(count_brewfile_entries "$brewfile_path" brew)"
cask_count="$(count_brewfile_entries "$brewfile_path" cask)"
log_preview \
"Would install ${formula_count} Homebrew formulae and ${cask_count} casks from ${COLOR_PATH}${brewfile_path}${COLOR_RESET}"
log_preview "Use --dry-run --verbose to expand Brewfile entries"
fi
else
execute_with_log brew bundle install --file "$brewfile_path"
fi
log_task "Cleaning up Homebrew..."
execute_with_log brew cleanup
if ! execute_with_log brew doctor; then
log_warn "Homebrew doctor reported issues; continuing setup."
fi
}
configure_shell_module() {
local fish_bin=""
local current_shell=""
if [[ "$MODULE_SHELL" != "true" ]]; then
log_task "Skipping fish shell configuration (module disabled)"
return
fi
fish_bin="$(command -v fish || true)"
if [[ -z "$fish_bin" ]]; then
if [[ "$DRY_RUN" == "true" ]]; then
fish_bin="${BREW_PREFIX}/bin/fish"
log_preview \
"fish not found in PATH; assuming ${COLOR_PATH}${fish_bin}${COLOR_RESET} after installation"
else
log_error "fish is not installed. Enable --brew first or install fish manually."
fi
fi
log_task "Setting fish as default shell..."
if ! grep -qs "${fish_bin}" "/etc/shells"; then