-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprep.sh
More file actions
1830 lines (1574 loc) · 52.8 KB
/
prep.sh
File metadata and controls
1830 lines (1574 loc) · 52.8 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
# =============================================================================
# macOS Setup Script
# =============================================================================
# HOW TO EDIT THIS FILE:
# - Dock items: Add/remove app paths in DOCK_ITEMS array
# - macOS defaults: Add entries to DEFAULTS_USER or DEFAULTS_ADMIN arrays
# Format: "domain|key|value|type" where type is: bool, string, int, float
# - Homebrew packages: Add/remove entries in BREW_FORMULAE/BREW_CASKS arrays
# - App Store apps: Add/remove entries in MAS_APPS array (format: "app_id|App Name")
# - Client profiles: Edit apply_client_profile() and run with --client NAME
# After editing, run: ./prep.sh
# =============================================================================
# -----------------------------------------------------------------------------
# Version (update this with each commit: V1.XX where XX = commit count)
# -----------------------------------------------------------------------------
VERSION="V1.17"
# -----------------------------------------------------------------------------
# Shell Options
# -----------------------------------------------------------------------------
set -u -o pipefail
# -----------------------------------------------------------------------------
# Configuration Arrays
# -----------------------------------------------------------------------------
# Default browser (set to empty string to skip)
DEFAULT_BROWSER="Google Chrome"
# Dock items - paths to applications (use "SPACER" for a spacer tile)
DOCK_ITEMS=(
"/Applications/Google Chrome.app"
"/Applications/Arc.app"
"/Applications/Google Drive.app"
"/Applications/1Password.app"
"/Applications/WhatsApp.app"
"/Applications/Slack.app"
"/Applications/Microsoft Word.app"
"/Applications/Microsoft Excel.app"
"/System/Applications/Notes.app"
"/System/Applications/Calendar.app"
"/Applications/Safari.app"
"/System/Applications/System Settings.app"
)
# Homebrew formulae (command-line tools)
BREW_FORMULAE=()
# Homebrew casks (GUI applications)
BREW_CASKS=()
# Mac App Store apps - format: "app_id|App Name"
MAS_APPS=(
"409201541|Pages"
"409203825|Numbers"
"409183694|Keynote"
)
# macOS defaults (user-level) - format: "domain|key|value|type"
# Types: bool, string, int, float
# Use "-g" or "NSGlobalDomain" for global domain
# Use "-currentHost" prefix for currentHost writes (e.g., "-currentHost|com.apple.Spotlight|MenuItemHidden|1|int")
DEFAULTS_USER=(
# General UI/UX
"NSGlobalDomain|NSNavPanelExpandedStateForSaveMode|true|bool"
"NSGlobalDomain|NSNavPanelExpandedStateForSaveMode2|true|bool"
"NSGlobalDomain|PMPrintingExpandedStateForPrint|true|bool"
"NSGlobalDomain|PMPrintingExpandedStateForPrint2|true|bool"
"com.apple.Siri|SiriPrefStashedStatusMenuVisible|false|bool"
"com.apple.Siri|VoiceTriggerUserEnabled|false|bool"
"-g|AppleWindowTabbingMode|always|string"
"com.apple.controlcenter|NSStatusItem Visible Bluetooth|true|bool"
"com.apple.controlcenter|NSStatusItem Visible Sound|true|bool"
"-currentHost|com.apple.Spotlight|MenuItemHidden|1|int"
# Finder
"com.apple.finder|ShowPathbar|true|bool"
"com.apple.finder|FXPreferredViewStyle|Nlsv|string"
"com.apple.finder|ShowStatusBar|true|bool"
"com.apple.finder|AppleShowAllFiles|true|bool"
"NSGlobalDomain|AppleShowAllExtensions|true|bool"
# Text Input
"NSGlobalDomain|NSAutomaticCapitalizationEnabled|false|bool"
"NSGlobalDomain|NSAutomaticSpellingCorrectionEnabled|false|bool"
# Bluetooth
"com.apple.BluetoothAudioAgent|Apple Bitpool Min (editable)|40|int"
# Network
"com.apple.NetworkBrowser|BrowseAllInterfaces|true|bool"
# Screenshots
"com.apple.screencapture|location|__HOME__/Downloads|string"
"com.apple.screencapture|type|png|string"
)
# Safari defaults - handled separately due to sandboxed container on macOS 14+
# Format: "key|value|type"
SAFARI_DEFAULTS=(
"IncludeDevelopMenu|true|bool"
"WebKitDeveloperExtrasEnabledPreferenceKey|true|bool"
"com.apple.Safari.ContentPageGroupIdentifier.WebKit2DeveloperExtrasEnabled|true|bool"
"AutoFillFromAddressBook|false|bool"
"AutoFillPasswords|false|bool"
"AutoFillCreditCardData|false|bool"
"AutoFillMiscellaneousForms|false|bool"
"SendDoNotTrackHTTPHeader|true|bool"
)
# macOS defaults (admin-level, requires sudo) - format: "domain|key|value|type"
DEFAULTS_ADMIN=(
"/Library/Preferences/com.apple.loginwindow|AdminHostInfo|HostName|string"
)
# Computer name - set to empty string to skip, or use "__SERIAL__" for serial number
COMPUTER_NAME="__SERIAL__"
# -----------------------------------------------------------------------------
# Runtime Variables (do not edit)
# -----------------------------------------------------------------------------
LOG_FILE="${HOME}/Downloads/prep-$(date '+%Y%m%d-%H%M%S').log"
FAILURES=()
WARNINGS=()
SKIPPED=()
STEP_NUM=0
TOTAL_STEPS=18
REVERT_DEFAULTS=false
CLIENT_PROFILE=""
SUDO_KEEPALIVE_PID=""
SUDO_INITIALIZED=false
ACCEPT_XCODE_LICENSE=false
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-${0}}")" && pwd)"
# Step result tracking (not used, kept for potential future use)
# -----------------------------------------------------------------------------
# Logging and Output Functions
# -----------------------------------------------------------------------------
log_to_file() {
printf "[%s] %s\n" "$(date '+%Y-%m-%d %H:%M:%S')" "$*" >> "$LOG_FILE"
}
log_verbose() {
# Only logs to file, not to console
log_to_file "$*"
}
log_success() {
log_to_file "OK: $*"
}
log_warn() {
log_to_file "WARN: $*"
WARNINGS+=("$*")
}
log_error() {
log_to_file "ERROR: $*"
FAILURES+=("$*")
}
log_skip() {
log_to_file "SKIP: $*"
SKIPPED+=("$*")
}
# Print step progress with dynamic status
print_step() {
local step_num="$1"
local total="$2"
local description="$3"
local status="${4:-}"
local detail="${5:-}"
# Pad step number for alignment
local padded_step
padded_step=$(printf "%2d" "$step_num")
# Create dots for alignment (50 chars total for description + dots)
local desc_len=${#description}
local dots_needed=$((45 - desc_len))
local dots=""
for ((i=0; i<dots_needed; i++)); do
dots="${dots}."
done
if [[ -n "$status" ]]; then
if [[ -n "$detail" ]]; then
printf "\r[%s/%d] %s%s %s (%s)\n" "$padded_step" "$total" "$description" "$dots" "$status" "$detail"
else
printf "\r[%s/%d] %s%s %s\n" "$padded_step" "$total" "$description" "$dots" "$status"
fi
else
printf "[%s/%d] %s%s " "$padded_step" "$total" "$description" "$dots"
fi
}
step_start() {
STEP_NUM=$((STEP_NUM + 1))
local description="$1"
print_step "$STEP_NUM" "$TOTAL_STEPS" "$description"
log_to_file "=== STEP $STEP_NUM/$TOTAL_STEPS: $description ==="
}
step_ok() {
local detail="${1:-}"
print_step "$STEP_NUM" "$TOTAL_STEPS" "${CURRENT_STEP_DESC:-Step}" "OK" "$detail"
}
step_fail() {
local detail="${1:-}"
print_step "$STEP_NUM" "$TOTAL_STEPS" "${CURRENT_STEP_DESC:-Step}" "FAILED" "$detail"
}
step_skip() {
local detail="${1:-}"
print_step "$STEP_NUM" "$TOTAL_STEPS" "${CURRENT_STEP_DESC:-Step}" "SKIPPED" "$detail"
}
# Track current step description for status updates
CURRENT_STEP_DESC=""
begin_step() {
STEP_NUM=$((STEP_NUM + 1))
CURRENT_STEP_DESC="$1"
print_step "$STEP_NUM" "$TOTAL_STEPS" "$1"
log_to_file "=== STEP $STEP_NUM/$TOTAL_STEPS: $1 ==="
}
# -----------------------------------------------------------------------------
# Command Execution Helpers
# -----------------------------------------------------------------------------
# Run command, log output, track success/failure
# Returns: 0 on success, 1 on failure
run_cmd() {
local desc="$1"
shift
log_verbose "Running: $*"
if "$@" >> "$LOG_FILE" 2>&1; then
log_success "$desc"
return 0
else
log_error "$desc"
return 1
fi
}
# Run command with sudo
run_cmd_admin() {
local desc="$1"
shift
ensure_sudo
log_verbose "Running (admin): sudo $*"
if sudo -n "$@" >> "$LOG_FILE" 2>&1; then
log_success "$desc"
return 0
else
log_error "$desc (admin session may have expired)"
return 1
fi
}
# Run command, warn on failure but don't track as error
run_optional() {
local desc="$1"
shift
log_verbose "Running (optional): $*"
if "$@" >> "$LOG_FILE" 2>&1; then
log_success "$desc"
return 0
else
log_warn "$desc"
return 1
fi
}
# Run optional command with sudo
run_optional_admin() {
local desc="$1"
shift
ensure_sudo
log_verbose "Running (optional admin): sudo $*"
if sudo -n "$@" >> "$LOG_FILE" 2>&1; then
log_success "$desc"
return 0
else
log_warn "$desc (admin)"
return 1
fi
}
# -----------------------------------------------------------------------------
# macOS Version Detection
# -----------------------------------------------------------------------------
# Get macOS major version number (e.g., 14 for Sonoma, 15 for Sequoia)
get_macos_major_version() {
sw_vers -productVersion | cut -d '.' -f 1
}
# Check if macOS version is at least the specified version
macos_version_at_least() {
local required_version=$1
local current_version
current_version=$(get_macos_major_version)
[[ "$current_version" -ge "$required_version" ]]
}
# -----------------------------------------------------------------------------
# Sudo Management
# -----------------------------------------------------------------------------
# Temporary file for sudo password (securely stored)
SUDO_PASSWORD_FILE=""
init_sudo() {
if [[ "$SUDO_INITIALIZED" == "true" ]]; then
return 0
fi
# Check if sudo command exists
if ! command -v sudo >/dev/null 2>&1; then
log_warn "sudo not available on this system"
return 1
fi
log_to_file "Requesting sudo credentials..."
printf "\nAdmin access is required. Please authenticate.\n"
# Read password securely from /dev/tty (works even when stdin is piped)
local sudo_password
printf "Password: "
read -r -s sudo_password < /dev/tty
printf "\n"
# Test if password is correct
if ! printf '%s\n' "$sudo_password" | sudo -S -v 2>/dev/null; then
log_error "Failed to obtain sudo credentials (incorrect password)"
return 1
fi
log_to_file "Sudo credentials obtained successfully"
# Store password securely in a temporary file for later use
# This is needed because Homebrew clears sudo timestamp during cask installations
SUDO_PASSWORD_FILE=$(mktemp)
chmod 600 "$SUDO_PASSWORD_FILE"
printf '%s' "$sudo_password" > "$SUDO_PASSWORD_FILE"
# Export the path so subshells can access it
export SUDO_PASSWORD_FILE
# Clear password from memory
sudo_password=""
# Keep sudo timestamp alive as a primary mechanism
(
while true; do
sleep 5
# Check if parent script is still running
kill -0 "$$" 2>/dev/null || exit 0
# Refresh sudo timestamp using stored password
if [[ -f "$SUDO_PASSWORD_FILE" ]]; then
cat "$SUDO_PASSWORD_FILE" | sudo -S -v >/dev/null 2>&1 || true
fi
done
) &
SUDO_KEEPALIVE_PID=$!
disown "$SUDO_KEEPALIVE_PID"
SUDO_INITIALIZED=true
log_success "Sudo initialized and keepalive started (PID: $SUDO_KEEPALIVE_PID)"
return 0
}
# Refresh sudo using stored password (call before operations that need sudo)
refresh_sudo() {
if [[ -n "${SUDO_PASSWORD_FILE:-}" && -f "$SUDO_PASSWORD_FILE" ]]; then
cat "$SUDO_PASSWORD_FILE" | sudo -S -v >/dev/null 2>&1 || true
else
sudo -v >/dev/null 2>&1 || true
fi
}
ensure_sudo() {
if [[ "$SUDO_INITIALIZED" != "true" ]]; then
init_sudo
fi
}
cleanup_sudo() {
# Suppress job control messages (prevents "Terminated" output)
set +m 2>/dev/null || true
local cleaned=false
# Kill the keepalive background process
if [[ -n "${SUDO_KEEPALIVE_PID:-}" ]]; then
kill "$SUDO_KEEPALIVE_PID" >/dev/null 2>&1 || true
wait "$SUDO_KEEPALIVE_PID" 2>/dev/null || true
log_to_file "Sudo keepalive process stopped"
cleaned=true
fi
# Securely remove the password file
if [[ -n "${SUDO_PASSWORD_FILE:-}" && -f "$SUDO_PASSWORD_FILE" ]]; then
rm -f "$SUDO_PASSWORD_FILE" 2>/dev/null || true
log_to_file "Sudo password file removed"
cleaned=true
fi
# Invalidate sudo timestamp
if command -v sudo >/dev/null 2>&1; then
sudo -k >/dev/null 2>&1 || true
log_to_file "Sudo timestamp invalidated"
fi
# Show clean terminal message if we cleaned something
if [[ "$cleaned" == "true" ]]; then
printf "\n\033[0;32m[OK]\033[0m Cleanup complete (sudo credentials cleared)\n"
fi
}
test_sudo() {
# Test if sudo is currently available without prompting
if sudo -n true 2>/dev/null; then
return 0
fi
return 1
}
# -----------------------------------------------------------------------------
# Universal Array Processing Functions
# -----------------------------------------------------------------------------
# Apply defaults from array
# Array format: "domain|key|value|type"
# Special: "-g" for global domain, "-currentHost|domain" for currentHost writes
# Special: "__HOME__" in value is replaced with $HOME
# Usage: apply_defaults false "${DEFAULTS_USER[@]}" or apply_defaults true "${DEFAULTS_ADMIN[@]}"
apply_defaults() {
local use_sudo=$1
shift
local defaults_arr=("$@")
local success_count=0
local fail_count=0
local total=${#defaults_arr[@]}
if [[ $total -eq 0 ]]; then
echo "0/0"
return 0
fi
local entry domain key value dtype
for entry in "${defaults_arr[@]}"; do
# Skip empty entries
[[ -z "$entry" ]] && continue
# Parse entry
IFS='|' read -r domain key value dtype <<< "$entry"
# Replace __HOME__ placeholder
value="${value//__HOME__/$HOME}"
# Build defaults command
local cmd_args=()
local is_currenthost=false
# Check for -currentHost prefix
if [[ "$domain" == "-currentHost" ]]; then
# Format: -currentHost|actual_domain|key|value|type
is_currenthost=true
IFS='|' read -r _ domain key value dtype <<< "$entry"
value="${value//__HOME__/$HOME}"
fi
# Determine type flag
local type_flag=""
case "$dtype" in
bool) type_flag="-bool" ;;
string) type_flag="-string" ;;
int) type_flag="-int" ;;
float) type_flag="-float" ;;
*) type_flag="-string" ;;
esac
# Build and execute command
local desc="Set $domain $key"
local result=0
if [[ "$is_currenthost" == "true" ]]; then
if [[ "$use_sudo" == "true" ]]; then
sudo -n defaults -currentHost write "$domain" "$key" "$type_flag" "$value" >> "$LOG_FILE" 2>&1 || result=1
else
defaults -currentHost write "$domain" "$key" "$type_flag" "$value" >> "$LOG_FILE" 2>&1 || result=1
fi
else
if [[ "$use_sudo" == "true" ]]; then
sudo -n defaults write "$domain" "$key" "$type_flag" "$value" >> "$LOG_FILE" 2>&1 || result=1
else
defaults write "$domain" "$key" "$type_flag" "$value" >> "$LOG_FILE" 2>&1 || result=1
fi
fi
if [[ $result -eq 0 ]]; then
log_success "$desc = $value"
((success_count++))
else
log_error "$desc"
((fail_count++))
fi
done
echo "$success_count/$total"
return $fail_count
}
# Revert defaults from array (delete the keys)
# Usage: revert_defaults false "${DEFAULTS_USER[@]}" or revert_defaults true "${DEFAULTS_ADMIN[@]}"
revert_defaults() {
local use_sudo=$1
shift
local defaults_arr=("$@")
local success_count=0
local total=${#defaults_arr[@]}
if [[ $total -eq 0 ]]; then
echo "0/0"
return 0
fi
local entry domain key value dtype
for entry in "${defaults_arr[@]}"; do
[[ -z "$entry" ]] && continue
IFS='|' read -r domain key value dtype <<< "$entry"
local is_currenthost=false
if [[ "$domain" == "-currentHost" ]]; then
is_currenthost=true
IFS='|' read -r _ domain key value dtype <<< "$entry"
fi
local desc="Revert $domain $key"
if [[ "$is_currenthost" == "true" ]]; then
if [[ "$use_sudo" == "true" ]]; then
sudo -n defaults -currentHost delete "$domain" "$key" >> "$LOG_FILE" 2>&1 && ((success_count++)) || log_warn "$desc"
else
defaults -currentHost delete "$domain" "$key" >> "$LOG_FILE" 2>&1 && ((success_count++)) || log_warn "$desc"
fi
else
if [[ "$use_sudo" == "true" ]]; then
sudo -n defaults delete "$domain" "$key" >> "$LOG_FILE" 2>&1 && ((success_count++)) || log_warn "$desc"
else
defaults delete "$domain" "$key" >> "$LOG_FILE" 2>&1 && ((success_count++)) || log_warn "$desc"
fi
fi
done
echo "$success_count/$total"
}
# Check if Terminal has Full Disk Access (required for Safari prefs on macOS 14+)
# Returns 0 if FDA is granted, 1 if not
check_full_disk_access() {
local test_file="${HOME}/Library/Containers/com.apple.Safari/Data/Library/Preferences/.fda_test_$$"
# Try to create a test file in Safari's container
if touch "$test_file" 2>/dev/null; then
rm -f "$test_file" 2>/dev/null
return 0
fi
return 1
}
# Prompt user to grant Full Disk Access to Terminal (macOS 14+)
# Opens System Settings and waits for user to grant access
prompt_full_disk_access() {
# Only needed on macOS 14+
if ! macos_version_at_least 14; then
return 0
fi
# Skip if no Safari defaults configured
if [[ ${#SAFARI_DEFAULTS[@]} -eq 0 ]]; then
return 0
fi
# Check if already granted
if check_full_disk_access; then
log_success "Full Disk Access already granted"
return 0
fi
# Get the terminal app name for display
local terminal_app="Terminal"
if [[ -n "${TERM_PROGRAM:-}" ]]; then
case "$TERM_PROGRAM" in
iTerm.app) terminal_app="iTerm" ;;
Apple_Terminal) terminal_app="Terminal" ;;
vscode) terminal_app="Visual Studio Code" ;;
*) terminal_app="$TERM_PROGRAM" ;;
esac
fi
printf "\n"
printf "┌─────────────────────────────────────────────────────────────────────┐\n"
printf "│ FULL DISK ACCESS REQUIRED │\n"
printf "├─────────────────────────────────────────────────────────────────────┤\n"
printf "│ macOS 14+ requires Full Disk Access to configure Safari settings. │\n"
printf "│ │\n"
printf "│ System Settings will open. Please: │\n"
printf "│ 1. Click the + button │\n"
printf "│ 2. Navigate to Applications > Utilities │\n"
printf "│ 3. Select '%s' and click Open │\n" "$terminal_app"
printf "│ 4. Enable the toggle for '%s' │\n" "$terminal_app"
printf "│ 5. Return here and press Enter to continue │\n"
printf "│ │\n"
printf "│ (You can skip this - Safari settings will be skipped) │\n"
printf "└─────────────────────────────────────────────────────────────────────┘\n"
printf "\n"
# Open System Settings to Full Disk Access
open "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles" 2>/dev/null || \
open "x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Privacy_AllFiles" 2>/dev/null || \
open "/System/Applications/System Settings.app" 2>/dev/null
printf "Press Enter after granting Full Disk Access (or to skip): "
read -r
# Check again
if check_full_disk_access; then
log_success "Full Disk Access granted"
return 0
else
log_warn "Full Disk Access not granted - Safari settings will be skipped"
return 1
fi
}
# Apply Safari defaults - handles sandboxed container on macOS 14+ (Sonoma/Sequoia)
# Usage: apply_safari_defaults "${SAFARI_DEFAULTS[@]}"
apply_safari_defaults() {
local safari_settings=("$@")
local success_count=0
local fail_count=0
local total=${#safari_settings[@]}
if [[ $total -eq 0 ]]; then
echo "0/0"
return 0
fi
# Determine the correct domain/path based on macOS version
# macOS 14+ (Sonoma/Sequoia) uses sandboxed container
local safari_domain="com.apple.Safari"
local safari_container="${HOME}/Library/Containers/com.apple.Safari/Data/Library/Preferences/com.apple.Safari.plist"
local use_container=false
if macos_version_at_least 14; then
use_container=true
log_verbose "macOS 14+ detected, using Safari container path"
# Ensure Safari container exists
if [[ ! -f "$safari_container" ]]; then
log_warn "Safari preferences file not found at $safari_container"
log_warn "Safari may need to be launched first to create preferences"
echo "0/$total"
return 1
fi
# Check for Full Disk Access - required on macOS 14+ for Safari container
if ! check_full_disk_access; then
log_warn "Terminal lacks Full Disk Access - cannot modify Safari preferences"
log_warn "To enable: System Settings > Privacy & Security > Full Disk Access > Add Terminal"
echo "SKIP:FDA"
return 2
fi
fi
local entry key value dtype
for entry in "${safari_settings[@]}"; do
[[ -z "$entry" ]] && continue
IFS='|' read -r key value dtype <<< "$entry"
# Determine type flag
local type_flag=""
case "$dtype" in
bool) type_flag="-bool" ;;
string) type_flag="-string" ;;
int) type_flag="-int" ;;
float) type_flag="-float" ;;
*) type_flag="-string" ;;
esac
local desc="Set Safari $key"
local result=0
if [[ "$use_container" == "true" ]]; then
# For macOS 14+, write directly to the container plist
defaults write "$safari_container" "$key" "$type_flag" "$value" >> "$LOG_FILE" 2>&1 || result=1
else
# For older macOS, use the standard domain
defaults write "$safari_domain" "$key" "$type_flag" "$value" >> "$LOG_FILE" 2>&1 || result=1
fi
if [[ $result -eq 0 ]]; then
log_success "$desc = $value"
((success_count++))
else
log_error "$desc"
((fail_count++))
fi
done
echo "$success_count/$total"
return $fail_count
}
# Revert Safari defaults
# Usage: revert_safari_defaults "${SAFARI_DEFAULTS[@]}"
revert_safari_defaults() {
local safari_settings=("$@")
local success_count=0
local total=${#safari_settings[@]}
if [[ $total -eq 0 ]]; then
echo "0/0"
return 0
fi
local safari_domain="com.apple.Safari"
local safari_container="${HOME}/Library/Containers/com.apple.Safari/Data/Library/Preferences/com.apple.Safari.plist"
local use_container=false
if macos_version_at_least 14; then
use_container=true
if [[ ! -f "$safari_container" ]]; then
echo "0/$total"
return 0
fi
fi
local entry key value dtype
for entry in "${safari_settings[@]}"; do
[[ -z "$entry" ]] && continue
IFS='|' read -r key value dtype <<< "$entry"
local desc="Revert Safari $key"
if [[ "$use_container" == "true" ]]; then
defaults delete "$safari_container" "$key" >> "$LOG_FILE" 2>&1 && ((success_count++)) || log_warn "$desc"
else
defaults delete "$safari_domain" "$key" >> "$LOG_FILE" 2>&1 && ((success_count++)) || log_warn "$desc"
fi
done
echo "$success_count/$total"
}
# Install Homebrew formulae from array
# Usage: install_brew_formulae "${BREW_FORMULAE[@]}"
install_brew_formulae() {
local formulae=("$@")
local success_count=0
local fail_count=0
local total=${#formulae[@]}
if [[ $total -eq 0 ]]; then
echo "0/0"
return 0
fi
# Try to find brew if not in PATH
local brew_cmd=""
if command -v brew >/dev/null 2>&1; then
brew_cmd="brew"
elif [[ -x /opt/homebrew/bin/brew ]]; then
brew_cmd="/opt/homebrew/bin/brew"
elif [[ -x /usr/local/bin/brew ]]; then
brew_cmd="/usr/local/bin/brew"
else
log_warn "Homebrew not installed, skipping formulae"
echo "0/$total"
return 1
fi
log_verbose "Using brew at: $brew_cmd"
log_verbose "Installing formulae: ${formulae[*]}"
local formula
for formula in "${formulae[@]}"; do
[[ -z "$formula" ]] && continue
log_verbose "Installing formula: $formula"
if "$brew_cmd" install "$formula" >> "$LOG_FILE" 2>&1; then
log_success "Install formula: $formula"
((success_count++))
else
log_error "Install formula: $formula"
((fail_count++))
fi
done
echo "$success_count/$total"
return $fail_count
}
# Install Homebrew casks from array
# Usage: install_brew_casks "${BREW_CASKS[@]}"
install_brew_casks() {
local casks=("$@")
local success_count=0
local fail_count=0
local total=${#casks[@]}
if [[ $total -eq 0 ]]; then
echo "0/0"
return 0
fi
# Try to find brew if not in PATH
local brew_cmd=""
if command -v brew >/dev/null 2>&1; then
brew_cmd="brew"
elif [[ -x /opt/homebrew/bin/brew ]]; then
brew_cmd="/opt/homebrew/bin/brew"
elif [[ -x /usr/local/bin/brew ]]; then
brew_cmd="/usr/local/bin/brew"
else
log_warn "Homebrew not installed, skipping casks"
echo "0/$total"
return 1
fi
log_verbose "Using brew at: $brew_cmd"
log_verbose "Installing casks: ${casks[*]}"
local cask
for cask in "${casks[@]}"; do
[[ -z "$cask" ]] && continue
# Refresh sudo before each cask (some have pkg installers that need sudo)
if [[ -n "${SUDO_PASSWORD_FILE:-}" && -f "$SUDO_PASSWORD_FILE" ]]; then
cat "$SUDO_PASSWORD_FILE" | sudo -S -v >/dev/null 2>&1 || true
fi
log_verbose "Installing cask: $cask"
if "$brew_cmd" install --cask "$cask" >> "$LOG_FILE" 2>&1; then
log_success "Install cask: $cask"
((success_count++))
else
log_error "Install cask: $cask"
((fail_count++))
fi
done
echo "$success_count/$total"
return $fail_count
}
# Install MAS apps from array
# Array format: "app_id|App Name"
# Usage: install_mas_apps "${MAS_APPS[@]}"
install_mas_apps() {
local apps=("$@")
local success_count=0
local fail_count=0
local total=${#apps[@]}
if [[ $total -eq 0 ]]; then
echo "0/0"
return 0
fi
# Try to find mas if not in PATH
local mas_cmd=""
if command -v mas >/dev/null 2>&1; then
mas_cmd="mas"
elif [[ -x /opt/homebrew/bin/mas ]]; then
mas_cmd="/opt/homebrew/bin/mas"
elif [[ -x /usr/local/bin/mas ]]; then
mas_cmd="/usr/local/bin/mas"
else
log_warn "mas not installed, skipping App Store apps"
echo "0/$total"
return 1
fi
local entry app_id app_name
for entry in "${apps[@]}"; do
[[ -z "$entry" ]] && continue
app_id="${entry%%|*}"
app_name="${entry#*|}"
if [[ -z "$app_id" || "$app_id" == "$app_name" ]]; then
log_warn "Invalid MAS entry: $entry"
((fail_count++))
continue
fi
if "$mas_cmd" install "$app_id" >> "$LOG_FILE" 2>&1; then
log_success "Install App Store: $app_name"
((success_count++))
else
log_error "Install App Store: $app_name"
((fail_count++))
fi
done
echo "$success_count/$total"
return $fail_count
}
# Get dockutil command path
get_dockutil_cmd() {
if command -v dockutil >/dev/null 2>&1; then
echo "dockutil"
elif [[ -x /opt/homebrew/bin/dockutil ]]; then
echo "/opt/homebrew/bin/dockutil"
elif [[ -x /usr/local/bin/dockutil ]]; then
echo "/usr/local/bin/dockutil"
else
echo ""
fi
}
# Verify dock configuration by checking if expected items are present
# Returns 0 if dock matches expected items, 1 otherwise
verify_dock() {
local items=("$@")
local dockutil_cmd
dockutil_cmd=$(get_dockutil_cmd)
if [[ -z "$dockutil_cmd" ]]; then
return 1
fi
# Get current dock items
local current_dock
current_dock=$("$dockutil_cmd" --list 2>/dev/null | cut -f1)
# Check if each expected app is in the dock
local item app_name
local missing=0
for item in "${items[@]}"; do
[[ -z "$item" ]] && continue
[[ "$item" == "SPACER" ]] && continue
# Extract app name from path
app_name=$(basename "$item" .app)
if ! echo "$current_dock" | grep -q "$app_name"; then
log_verbose "Dock verification: missing $app_name"
((missing++))
fi
done
if [[ $missing -eq 0 ]]; then
return 0
else
return 1
fi
}
# Configure dock from array with retry logic
# Usage: configure_dock "${DOCK_ITEMS[@]}"
configure_dock() {
local items=("$@")
local success_count=0
local total=${#items[@]}
local max_retries=5
local retry=0
if [[ $total -eq 0 ]]; then
echo "0/0"
return 0
fi
# Try to find dockutil if not in PATH
local dockutil_cmd
dockutil_cmd=$(get_dockutil_cmd)
if [[ -z "$dockutil_cmd" ]]; then
log_warn "dockutil not installed, skipping dock configuration"
echo "0/$total"
return 1
fi
while [[ $retry -lt $max_retries ]]; do
success_count=0
if [[ $retry -gt 0 ]]; then
log_verbose "Dock configuration retry $retry/$max_retries"
sleep 2
fi
# Clear existing dock items
"$dockutil_cmd" --remove all --no-restart >> "$LOG_FILE" 2>&1
if [[ $retry -eq 0 ]]; then