Repository navigation
Expand file tree
/
Copy pathbootstrap.sh
More file actions
executable file
·667 lines (608 loc) · 24.9 KB
/
Copy pathbootstrap.sh
File metadata and controls
executable file
·667 lines (608 loc) · 24.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
#!/bin/sh
#
# Idempotent machine setup using mise.
#
# Usage:
# ~/.dotfiles/bootstrap.sh [--force|--host <hostname>]
#
set -eu
BOOTSTRAP_UPDATED="2026-10-21 (pull watchdog, dangling-link cleanup)"
DOTFILES_REPO_URL="${DOTFILES_REPO_URL:-https://github.com/megalithic/dotfiles.git}"
DOTFILES_DIR="${DOTFILES_DIR:-$HOME/.dotfiles}"
BOOTSTRAP_MISE_CONFIG="$DOTFILES_DIR/config/mise/config.toml"
FORCE_HOST="${HOST:-}" # desired hostname; skip hostname prompt if set
FORCE=0 # --force: pass force flags to all sub-commands
BOOTSTRAP_INSTALL_ROSETTA="${BOOTSTRAP_INSTALL_ROSETTA:-0}"
MISE_INSTALL_PATH="$HOME/.local/bin/mise"
HOMEBREW_NO_ASK=1
export HOMEBREW_NO_ASK
export DOTFILES_DIR
export MISE_INSTALL_PATH
COLOR_RESET="$(printf '\033[0m')"
COLOR_BLUE="$(printf '\033[34m')"
COLOR_BOLD_RED="$(printf '\033[1;31m')"
COLOR_BOLD_GREEN="$(printf '\033[1;32m')"
COLOR_ITALIC_YELLOW="$(printf '\033[3;33m')"
# -- helpers --
say() { printf ' :: %s\n' "$*"; }
ok() { printf ' %s[✓]%s %s\n' "$COLOR_BOLD_GREEN" "$COLOR_RESET" "$*"; }
warn() { printf ' %s[!]%s %s\n' "$COLOR_ITALIC_YELLOW" "$COLOR_RESET" "$*" >&2; }
info() { printf ' %s[.]%s %s\n' "$COLOR_BLUE" "$COLOR_RESET" "$1"; }
die() {
printf ' %s[✗]%s %s\n' "$COLOR_BOLD_RED" "$COLOR_RESET" "$1" >&2
exit 1
}
header() {
printf '\n'
printf '\n'
printf ' ┌┬┐┌─┐┌─┐┌─┐┬ ┬┌┬┐┬ ┬┬┌─┐\n'
printf ' │││├┤ │ ┬├─┤│ │ │ ├─┤││ dotfiles\n'
printf ' ┴ ┴└─┘└─┘┴ ┴┴─┘┴ ┴ ┴ ┴┴└─┘\n'
printf '\n'
printf ' updated: %s\n' "$BOOTSTRAP_UPDATED"
printf ' bootstrapping...\n'
printf '\n'
}
ensure_tty() {
if ! { : </dev/tty; } 2>/dev/null; then
die "$1 requires an interactive terminal; pass --host <name> or set HOST=<name>"
fi
}
ask_tty() {
ask_prompt="$1"
ensure_tty "$ask_prompt"
while :; do
printf ' [?] %s ' "$ask_prompt" >/dev/tty
IFS= read -r ask_reply </dev/tty || die "Could not read response from terminal"
ask_reply=$(printf '%s' "$ask_reply" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
if [ -n "$ask_reply" ]; then
printf '%s\n' "$ask_reply"
return 0
fi
warn "Response required."
done
}
ask_tty_default() {
ask_prompt="$1"
ask_default="$2"
ensure_tty "$ask_prompt"
printf ' [?] %s ' "$ask_prompt" >/dev/tty
IFS= read -r ask_reply </dev/tty || die "Could not read response from terminal"
ask_reply=$(printf '%s' "$ask_reply" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
printf '%s\n' "${ask_reply:-$ask_default}"
}
normalize_hostname() {
printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9-' '-' | sed 's/--*/-/g;s/^-//;s/-$//'
}
use_standalone_mise() {
PATH="$HOME/.local/bin:$PATH"
export PATH
# Override nix-managed gitconfig that rewrites https://github.com/ → ssh://
# (nix/home/common/programs/git/gitconfig). mise uses libgit2 which reads
# ~/.gitconfig — the rewrite forces plugin fetches onto SSH, which fails
# in non-interactive contexts without an agent. /dev/null skips the global
# config entirely; plugin fetches are read-only public clones that don't
# need user.name, gpg, or other global settings.
export GIT_CONFIG_GLOBAL=/dev/null
hash -r 2>/dev/null || true
}
install_mise_standalone() {
info "Installing mise to ~/.local/bin via https://mise.run..."
MISE_INSTALL_PATH="$MISE_INSTALL_PATH" sh -c "$(curl -fsSL https://mise.run)" || {
warn "Standalone mise install failed."
return 1
}
use_standalone_mise
}
ensure_mise_standalone() {
if [ ! -x "$MISE_INSTALL_PATH" ]; then
install_mise_standalone
else
use_standalone_mise
info "Updating standalone mise..."
"$MISE_INSTALL_PATH" self-update --yes || install_mise_standalone
fi
use_standalone_mise
[ "$(command -v mise 2>/dev/null)" = "$MISE_INSTALL_PATH" ] || die "Expected standalone mise at $MISE_INSTALL_PATH in PATH"
ok "$(mise --version)"
}
# nix-homebrew pins Homebrew taps as symlinks into /nix/store. After nix is
# uninstalled (or while it's read-only) those links break `brew update` and
# `brew tap` with 'Permission denied'. Unlink them; brew works API-based
# without any taps and re-clones real ones on demand.
repair_nix_pinned_taps() {
brew_repo=$(brew --repository 2>/dev/null) || return 0
[ -n "$brew_repo" ] || return 0
taps_dir="$brew_repo/Library/Taps"
for tap_path in "$taps_dir" "$taps_dir"/* "$taps_dir"/*/*; do
[ -L "$tap_path" ] || continue
case "$(readlink "$tap_path")" in
/nix/store/*)
warn "Removing nix-pinned Homebrew tap link: $tap_path"
rm -f "$tap_path"
;;
esac
done
[ -d "$taps_dir" ] || mkdir -p "$taps_dir"
}
# Unlink a symlink that points into the read-only /nix/store; its parent dir
# is writable even though the target is not.
remove_store_link() {
[ -L "$1" ] || return 0
case "$(readlink "$1")" in
/nix/store/*)
info "Removing nix-managed symlink: $1"
rm -f "$1"
;;
esac
}
# Home Manager leaves symlinks into /nix/store at paths mise manages;
# `mise dotfiles apply --force` tries to rm *through* dir symlinks and dies
# with EACCES in the store. Unlink store symlinks at managed targets (and one
# level inside real dirs, for symlink-each entries) before applying.
clean_nix_managed_targets() {
sed -n '/^\[dotfiles\]/,/^\[/s/^"\(~\/[^"]*\)".*/\1/p' "$BOOTSTRAP_MISE_CONFIG" |
while IFS= read -r target; do
path="$HOME${target#\~}"
remove_store_link "$path"
# A dangling symlink at a managed target (e.g. ~/bin -> /nix/store/...
# after /nix is uninstalled) blocks apply; clear it so apply can relink.
if [ -L "$path" ] && [ ! -e "$path" ]; then
info "Removing dangling symlink at managed target: $path"
rm -f "$path"
fi
if [ -d /nix/store ] && [ -d "$path" ] && [ ! -L "$path" ]; then
for entry in "$path"/* "$path"/.[!.]*; do
remove_store_link "$entry"
done
fi
done
}
dotfiles_default_branch() {
default_branch=$(git -C "$DOTFILES_DIR" symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's|^origin/||')
printf '%s' "${default_branch:-main}"
}
# `git pull` refuses to run on a detached HEAD; check out the default branch first.
ensure_dotfiles_branch() {
if git -C "$DOTFILES_DIR" symbolic-ref -q HEAD >/dev/null 2>&1; then
return 0
fi
checkout_branch=$(dotfiles_default_branch)
warn "$DOTFILES_DIR is on a detached HEAD; checking out $checkout_branch."
git -C "$DOTFILES_DIR" checkout "$checkout_branch"
}
# Auto-stash local changes so checkout/pull never abort on a dirty tree.
# Recover later with: git -C ~/.dotfiles stash list / stash pop
stash_dotfiles_changes() {
[ -n "$(git -C "$DOTFILES_DIR" status --porcelain 2>/dev/null)" ] || return 0
warn "$DOTFILES_DIR has local changes; stashing them (recover with 'git stash pop')."
git -C "$DOTFILES_DIR" stash push -u -m "bootstrap auto-stash $(date +%Y%m%d-%H%M%S)"
}
# The configured remote is ssh://..., which HANGS (not fails) when the ssh
# agent (e.g. 1Password) is unavailable. Bound the attempt with a watchdog;
# on timeout or failure, fall back to an HTTPS pull with scrubbed git config
# (the user gitconfig rewrites https://github.com/ -> ssh://, which would
# hang the same way). The interactive menu below remains as the last resort.
DOTFILES_PULL_TIMEOUT="${DOTFILES_PULL_TIMEOUT:-45}"
pull_configured_remote() {
git -C "$DOTFILES_DIR" pull --ff-only &
pull_pid=$!
(
sleep "$DOTFILES_PULL_TIMEOUT"
kill "$pull_pid" 2>/dev/null
) &
watchdog_pid=$!
wait "$pull_pid" 2>/dev/null
pull_rc=$?
kill "$watchdog_pid" 2>/dev/null
wait "$watchdog_pid" 2>/dev/null
return "$pull_rc"
}
pull_dotfiles_https() {
GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \
git -C "$DOTFILES_DIR" pull --ff-only "$DOTFILES_REPO_URL" "$(dotfiles_default_branch)"
}
pull_dotfiles() {
stash_dotfiles_changes && ensure_dotfiles_branch || return 1
if pull_configured_remote; then
return 0
fi
warn "Configured-remote pull failed or timed out; trying HTTPS fallback."
pull_dotfiles_https
}
update_dotfiles_checkout() {
info "Updating $DOTFILES_DIR..."
if pull_dotfiles; then
return 0
fi
while :; do
warn "Could not update $DOTFILES_DIR with its configured remote."
say "If SSH auth needs attention, unlock/fix it now, then retry."
say "Options:"
say " [r]etry configured remote"
say " [h]ttps fallback using $DOTFILES_REPO_URL"
say " [s]tash local changes, then use HTTPS fallback"
say " [a]bort"
UPDATE_CHOICE=$(ask_tty "Update action [r/h/s/a]:")
case "$UPDATE_CHOICE" in
r | R | retry)
pull_dotfiles && return 0
;;
h | H | https)
ensure_dotfiles_branch &&
GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 git -C "$DOTFILES_DIR" pull --ff-only "$DOTFILES_REPO_URL" HEAD && return 0
;;
s | S | stash)
git -C "$DOTFILES_DIR" stash push -u -m "bootstrap before update $(date +%Y%m%d-%H%M%S)" || warn "Stash failed."
ensure_dotfiles_branch &&
GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 git -C "$DOTFILES_DIR" pull --ff-only "$DOTFILES_REPO_URL" HEAD && return 0
;;
a | A | abort)
die "Could not update $DOTFILES_DIR; fix git auth/local changes and retry"
;;
*)
warn "Choose r, h, s, or a."
;;
esac
done
}
usage() {
printf 'usage: bootstrap.sh [--force] [--host <name>]\n'
printf ' --force overwrite conflicting dotfile targets (mise dotfiles apply --force,\n'
printf ' mise bootstrap --force-dotfiles)\n'
printf ' --host <name> set macOS hostname and skip prompt\n'
}
while [ $# -gt 0 ]; do
case "$1" in
--force) FORCE=1 ;;
--host)
shift
[ $# -gt 0 ] || die "--host requires a value"
FORCE_HOST="$1"
;;
-h | --help)
usage
exit 0
;;
*)
usage >&2
die "Unknown argument: $1"
;;
esac
shift
done
# flags forwarded to mise sub-commands (word-split on purpose; flags contain no spaces)
MISE_DOTFILES_FLAGS=""
# mise 2026.7.5 launchd apply fails on clean Tahoe VMs with launchctl bootout
# EIO before services converge. Its user step also calls chsh, which prompts
# for a password on macOS. Skip both and handle the login shell below with sudo.
# Tools are NOT skipped — mise bootstrap installs the full toolchain. Never
# skip them: auto_install is off, so nothing else installs tools on first use.
# Tasks remain enabled for post-tool bootstrap work. Secrets are resolved
# directly by fnox; bootstrap never renders or sources secret files.
MISE_BOOTSTRAP_FLAGS="--skip launchd --skip user"
if [ "$FORCE" = 1 ]; then
MISE_DOTFILES_FLAGS="$MISE_DOTFILES_FLAGS --force"
MISE_BOOTSTRAP_FLAGS="$MISE_BOOTSTRAP_FLAGS --force-dotfiles"
fi
header
[ "$(uname -s)" = "Darwin" ] || die "macOS only."
[ "$(id -u)" -ne 0 ] || die "Do not run as root."
# Cache sudo credentials early so later sudo ops (hostname, xcode license,
# fish shell, app rescue) never re-prompt. A background loop refreshes the
# timestamp every 60s; without this, the default 5-minute timeout expires
# during long-running steps (CLT install, mise bootstrap packages/tools).
# sudo -nv checks non-interactively first; only prompt if the timestamp is
# expired (e.g. re-running bootstrap minutes after a prior sudo).
sudo -nv 2>/dev/null || sudo -v || die "sudo authentication failed; bootstrap needs administrator privileges"
(
while true; do
# -nv never prompts; on failure just keep retrying — the next sudo
# in the main process will prompt if the timestamp truly expired.
sudo -nv 2>/dev/null
sleep 60
done
) &
SUDO_KEEPALIVE_PID=$!
# Clean up the background loop on exit (normal or error). `wait` after kill
# reaps the job synchronously so the shell doesn't print a "Terminated: 15"
# job-control notice.
trap 'kill "$SUDO_KEEPALIVE_PID" 2>/dev/null || true; wait "$SUDO_KEEPALIVE_PID" 2>/dev/null || true' EXIT
install_clt_noninteractive() {
clt_marker="/tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress"
touch "$clt_marker"
clt_label=$(softwareupdate --list 2>&1 |
sed -n 's/^[[:space:]]*\* Label: \(Command Line Tools for Xcode.*\)$/\1/p' |
tail -1)
if [ -z "$clt_label" ]; then
rm -f "$clt_marker"
die "Could not find Command Line Tools in softwareupdate catalog"
fi
info "Installing $clt_label via softwareupdate..."
if ! sudo softwareupdate --install "$clt_label" --verbose; then
rm -f "$clt_marker"
die "Command Line Tools install failed"
fi
rm -f "$clt_marker"
if [ -d /Library/Developer/CommandLineTools ]; then
sudo xcode-select --switch /Library/Developer/CommandLineTools
fi
xcode-select -p >/dev/null 2>&1 || die "Command Line Tools install did not complete"
}
# CLT first: everything below (brew, git, compilers) depends on it.
if xcode-select -p >/dev/null 2>&1; then
ok "CLT installed: $(xcode-select -p)"
else
info "Command Line Tools not installed; installing now."
install_clt_noninteractive
ok "CLT installed: $(xcode-select -p)"
fi
if ! command -v brew >/dev/null 2>&1; then
info "Installing Homebrew (needs an administrator password)..."
id -Gn | grep -qw admin || die "Homebrew install requires an administrator account; $(id -un) is not in the admin group"
# NONINTERACTIVE installs refuse to prompt for sudo — credentials were
# cached at startup; verify they're still valid (prompt only if expired).
sudo -nv 2>/dev/null || sudo -v || die "sudo authentication failed; Homebrew install needs it"
NONINTERACTIVE=1 HOMEBREW_NO_ANALYTICS=1 HOMEBREW_NO_ENV_HINTS=1 /bin/bash -c \
"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
fi
if [ -x /opt/homebrew/bin/brew ]; then
eval "$(/opt/homebrew/bin/brew shellenv)"
elif [ -x /usr/local/bin/brew ]; then
eval "$(/usr/local/bin/brew shellenv)"
fi
# heal nix-homebrew leftovers before anything uses brew (cheap, idempotent)
repair_nix_pinned_taps
ensure_mise_standalone
HOST=""
CURRENT_HOST=$(normalize_hostname "$(uname -n | cut -d. -f1)")
if [ -n "$FORCE_HOST" ]; then
HOST=$(normalize_hostname "$FORCE_HOST")
[ -n "$HOST" ] || die "--host cannot be empty after normalization"
ok "Host override: $HOST"
else
REPLY=$(ask_tty_default "Hostname [$CURRENT_HOST]:" "$CURRENT_HOST")
HOST=$(normalize_hostname "$REPLY")
[ -n "$HOST" ] || die "Hostname cannot be empty after normalization"
fi
# Host-specific mise config: mise merges ~/.config/mise/config.$MISE_ENV.toml
# on top of the global config (shell init exports this for later sessions).
export MISE_ENV="$HOST"
if [ "$HOST" != "$CURRENT_HOST" ]; then
say "Switching macOS hostname: $CURRENT_HOST -> $HOST"
sudo scutil --set ComputerName "$HOST"
sudo scutil --set LocalHostName "$HOST"
sudo scutil --set HostName "$HOST"
sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.smb.server NetBIOSName -string "$HOST"
ok "Hostname set to $HOST"
fi
xcode_license_check=$(xcodebuild -license check 2>&1 || true)
case "$xcode_license_check" in
*"requires Xcode"*"CommandLineTools"*)
info "Skipping Xcode license check (CLT-only install)."
;;
"")
:
;;
*)
warn "Xcode license not accepted."
sudo xcodebuild -license accept
ok "Xcode license accepted"
;;
esac
# Rosetta is optional for this bootstrap path: Homebrew and mise install native
# arm64 packages on Apple Silicon. Keep it opt-in because Tahoe's successful
# Rosetta installer prints Apple Package Authoring Error noise.
if [ "$(uname -m)" = "arm64" ]; then
if /usr/bin/pgrep -q oahd 2>/dev/null; then
ok "Rosetta 2 installed"
elif [ "$BOOTSTRAP_INSTALL_ROSETTA" = 1 ]; then
say "Installing Rosetta 2..."
softwareupdate --install-rosetta --agree-to-license
else
info "Skipping Rosetta 2 install (set BOOTSTRAP_INSTALL_ROSETTA=1 to install)."
fi
fi
if [ -d "$DOTFILES_DIR/.git" ]; then
update_dotfiles_checkout
else
info "Cloning into $DOTFILES_DIR..."
mkdir -p "$(dirname "$DOTFILES_DIR")"
git clone "$DOTFILES_REPO_URL" "$DOTFILES_DIR"
fi
# Pre-apply dotfiles so the global ~/.config/mise/config.toml ([tools]) is in place before
# `mise bootstrap` resolves tools on a first-ever run. Cheap + idempotent — keep it.
# NOTE: plain sequential statements — wrapping these in `cd || { } && { }`
# suppresses `set -e` inside the block, letting mise failures slip through.
cd "$DOTFILES_DIR" || die "Unable to change to $DOTFILES_DIR"
[ -f "$BOOTSTRAP_MISE_CONFIG" ] || die "Missing $BOOTSTRAP_MISE_CONFIG; checkout is stale or incomplete"
# Keep bootstrap pinned to the repo-managed global config dir, not whichever
# ~/.config/mise may exist on the machine already. A config dir (not a pinned
# file) also loads the config.$MISE_ENV.toml host overlay.
MISE_CONFIG_DIR="$(dirname "$BOOTSTRAP_MISE_CONFIG")"
export MISE_CONFIG_DIR
info "Trusting mise global config..."
mise trust "$BOOTSTRAP_MISE_CONFIG"
[ -f "$MISE_CONFIG_DIR/config.$HOST.toml" ] && mise trust "$MISE_CONFIG_DIR/config.$HOST.toml"
clean_nix_managed_targets
info "Applying dotfiles..."
# shellcheck disable=SC2086 # intentional word-splitting of flag strings
if ! mise dotfiles apply --yes $MISE_DOTFILES_FLAGS; then
warn "dotfiles apply refused to overwrite existing files."
say "Re-run with --force to overwrite them, e.g.:"
# shellcheck disable=SC2016 # literal one-liner for the user to copy
say ' bash -c "$(curl -fsSL https://raw.githubusercontent.com/megalithic/dotfiles/HEAD/bootstrap.sh)" -- --force'
die "dotfiles apply failed"
fi
ok "done applying dotfiles."
MISE_BOOTSTRAP_LOG="${TMPDIR:-/tmp}/bootstrap-mise-$$.log"
MISE_BOOTSTRAP_STATUS="${TMPDIR:-/tmp}/bootstrap-mise-$$.status"
# Run mise bootstrap while capturing output so failures can be inspected.
attempt_mise_bootstrap() {
# shellcheck disable=SC2086 # intentional word-splitting of flag strings
# `|| printf` keeps `set -e` from killing the subshell before status is written
{
mise bootstrap --yes $MISE_BOOTSTRAP_FLAGS 2>&1 &&
printf '%s' 0 >"$MISE_BOOTSTRAP_STATUS" ||
printf '%s' "$?" >"$MISE_BOOTSTRAP_STATUS"
} | tee "$MISE_BOOTSTRAP_LOG"
[ "$(cat "$MISE_BOOTSTRAP_STATUS" 2>/dev/null)" = 0 ]
}
# If mise failed renaming an app bundle in /Applications, try moving it aside
# with sudo. This rescues root-owned bundles (previous installer/MDM). It does
# NOT rescue the App Management TCC block — macOS attributes sudo'd commands to
# the spawning terminal, so TCC denies root exactly the same.
sudo_rescue_app_rename() {
blocked=$(sed -n 's/.*failed rename: \(\/Applications\/[^ ]*\.app\) ->.*/\1/p' "$MISE_BOOTSTRAP_LOG" | head -1)
[ -n "$blocked" ] || return 1
[ -e "$blocked" ] || return 1
warn "mise could not rename $blocked; trying with sudo..."
if sudo mv "$blocked" "${blocked%.app}.pre-mise-$(date +%s).app"; then
ok "Moved aside with sudo (kept as backup); retrying mise bootstrap."
return 0
fi
warn "sudo could not rename it either — that confirms the App Management TCC block (sudo cannot bypass TCC)."
return 1
}
# mise's brew backend refuses to link a formula when target files already
# exist but weren't created by mise or brew (left over from a previous
# nix-homebrew or manual brew install). Remove the conflicting files and
# let mise reinstall; brew will recreate them on the retry.
rescue_stale_brew_files() {
can_link=$(sed -n 's/.*cannot link \([^:]*\):.*/\1/p' "$MISE_BOOTSTRAP_LOG" | head -1)
[ -n "$can_link" ] || return 1
# Collect the file paths listed after the error line — they appear indented
# on subsequent lines until the next ERROR or blank line.
files=$(sed -n '/cannot link '"$can_link"'/,/^mise ERROR/{ /^ \//p; }' "$MISE_BOOTSTRAP_LOG" | sed 's/^ //')
[ -n "$files" ] || return 1
warn "mise brew cannot link $can_link — removing stale files from previous install..."
removed=0
while IFS= read -r f; do
[ -n "$f" ] || continue
if [ -e "$f" ]; then
info "Removing stale file: $f"
sudo rm -f "$f" && removed=1
fi
done <<EOF
$files
EOF
if [ "$removed" = 1 ]; then
ok "Removed stale files; retrying mise bootstrap."
return 0
fi
return 1
}
# mise launchd registration can trip over stale or half-written plists on first
# bootstrap. When bootout fails, remove the stale registration target and retry.
rescue_stuck_launchd_agent() {
plist=$(sed -n 's/.*launchctl bootout gui\/[0-9][0-9]* \([^`]*\.plist\).*/\1/p' "$MISE_BOOTSTRAP_LOG" | head -1)
[ -n "$plist" ] || return 1
label=$(basename "$plist" .plist)
warn "mise could not bootout stale launchd agent $label; removing stale registration target..."
launchctl bootout "gui/$(id -u)/$label" 2>/dev/null || true
[ ! -e "$plist" ] || rm -f "$plist"
ok "Cleared stale launchd agent $label; retrying mise bootstrap."
return 0
}
# Print failure guidance that matches what actually went wrong, based on the
# captured mise output — only the /Applications permission case is TCC.
explain_mise_bootstrap_failure() {
if grep -q 'failed rename: /Applications/.*Permission denied\|failed rename: /Applications/' "$MISE_BOOTSTRAP_LOG" 2>/dev/null &&
grep -q 'Permission denied' "$MISE_BOOTSTRAP_LOG" 2>/dev/null; then
say "'Permission denied' under /Applications usually means this terminal lacks"
say "the App Management permission. Opening System Settings at that pane..."
open "x-apple.systempreferences:com.apple.preference.security?Privacy_AppBundles" 2>/dev/null ||
say "(open System Settings -> Privacy & Security -> App Management manually)"
say "Enable it for this terminal. IMPORTANT: the grant only applies to a fresh"
say "terminal process — after toggling, fully quit this terminal app (Cmd+Q),"
say "reopen it, and re-run this bootstrap; retrying here will fail again."
say "If no toggle appears (MDM-managed work machine), delete the affected app"
say "via Finder (drag to Trash), then retry here."
return 0
fi
if grep -q 'cannot link.*these files already exist' "$MISE_BOOTSTRAP_LOG" 2>/dev/null; then
say "Stale Homebrew files from a previous install are blocking mise."
say "The bootstrap script attempted to remove them automatically; if you're still"
say "seeing this, run manually:"
grep 'cannot link' "$MISE_BOOTSTRAP_LOG" 2>/dev/null | head -1 | while IFS= read -r line; do
say " $line"
done
say "Delete the listed files with sudo rm, then re-run bootstrap."
return 0
fi
say "Errors from mise:"
grep 'ERROR' "$MISE_BOOTSTRAP_LOG" 2>/dev/null | tail -5 | while IFS= read -r line; do
say " $line"
done
say "Full log: $MISE_BOOTSTRAP_LOG (re-run with MISE_VERBOSE=1 for more)."
say "Fix the underlying issue, then retry."
}
run_mise_bootstrap() {
attempt_mise_bootstrap && return 0
if sudo_rescue_app_rename || rescue_stale_brew_files || rescue_stuck_launchd_agent; then
attempt_mise_bootstrap && return 0
fi
if ! { : </dev/tty; } 2>/dev/null; then
explain_mise_bootstrap_failure
die "mise bootstrap failed in non-interactive mode"
fi
while :; do
warn "mise bootstrap failed."
explain_mise_bootstrap_failure
say "Options:"
say " [r]etry mise bootstrap"
say " [c]ontinue without finishing mise bootstrap"
say " [a]bort"
BOOTSTRAP_CHOICE=$(ask_tty "Bootstrap action [r/c/a]:")
case "$BOOTSTRAP_CHOICE" in
r | R | retry)
attempt_mise_bootstrap && return 0
if sudo_rescue_app_rename || rescue_stuck_launchd_agent; then
attempt_mise_bootstrap && return 0
fi
;;
c | C | continue)
warn "Continuing with mise bootstrap unfinished; re-run bootstrap.sh (or 'mise bootstrap') after fixing permissions."
return 0
;;
a | A | abort)
die "mise bootstrap failed"
;;
*)
warn "Choose r, c, or a."
;;
esac
done
}
set_login_shell() {
fish_path="/opt/homebrew/bin/fish"
[ -x "$fish_path" ] || fish_path="$(command -v fish 2>/dev/null || true)"
[ -n "$fish_path" ] || die "fish is not installed; cannot set login shell"
if ! grep -qx "$fish_path" /etc/shells 2>/dev/null; then
info "Adding $fish_path to /etc/shells..."
printf '%s\n' "$fish_path" | sudo tee -a /etc/shells >/dev/null
fi
current_shell=$(dscl . -read "/Users/$(id -un)" UserShell 2>/dev/null | awk '{print $2}')
if [ "$current_shell" != "$fish_path" ]; then
info "Setting login shell to $fish_path..."
sudo dscl . -change "/Users/$(id -un)" UserShell "$current_shell" "$fish_path"
fi
ok "login shell: $fish_path"
}
info "Running mise bootstrap..."
run_mise_bootstrap
ok "done bootstrapping."
set_login_shell
# Kill the sudo keepalive loop before doctor (it runs in the background and
# the EXIT trap handles normal exits, but explicit cleanup is cleaner).
if [ -n "${SUDO_KEEPALIVE_PID:-}" ]; then
kill "$SUDO_KEEPALIVE_PID" 2>/dev/null || true
# Reap synchronously so sh doesn't print a "Terminated: 15" notice.
wait "$SUDO_KEEPALIVE_PID" 2>/dev/null || true
fi
if BOOTSTRAP_SKIP_TOOL_CHECK=1 ./mise/scripts/check-system; then
info "Done. Restart your terminal (login shell is now fish)."
else
warn "Finished, but some of the health checks failed."
info " Run 'mise run doctor' to investigate."
fi