-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmacdna.py
More file actions
2101 lines (1821 loc) Β· 74.4 KB
/
Copy pathmacdna.py
File metadata and controls
2101 lines (1821 loc) Β· 74.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
ββββββββββββββββββββββββββββββββββββββββββββββββ
β 𧬠M a c D N A v 3 β
β Capture Β· Deploy Β· Clone Your Mac β
β βββββββββββββββββββββββββββββββββββββββββββββββ£
β Author: cyberspartan77 β
β Version: 3.0 (Interactive Menu) β
β Date: March 2026 β
β βββββββββββββββββββββββββββββββββββββββββββββββ£
β Captures your Mac's full configuration DNA β
β and deploys it to any new machine. β
β β
β Just run: python3 macdna.py β
ββββββββββββββββββββββββββββββββββββββββββββββββ
"""
import subprocess
import json
import os
import sys
import shutil
import platform
import datetime
import plistlib
import glob as globmod
import re
import getpass
import hashlib
from pathlib import Path
import securityaudit
# βββββββββββββββββββββββββββββββββββββββββββββββ
# TERMINAL UI
# βββββββββββββββββββββββββββββββββββββββββββββββ
BOLD = "\033[1m"
DIM = "\033[2m"
RESET = "\033[0m"
GREEN = "\033[92m"
RED = "\033[91m"
YELLOW = "\033[93m"
CYAN = "\033[96m"
MAGENTA = "\033[95m"
WHITE = "\033[97m"
BG_BLUE = "\033[44m"
BG_RESET = "\033[49m"
APP_DIR = os.path.dirname(os.path.abspath(__file__))
PROFILES_DIR = os.path.join(APP_DIR, "profiles")
SETTINGS_FILE = os.path.join(APP_DIR, "settings.json")
# βββββββββββββββββββββββββββββββββββββββββββββββ
# SETTINGS ENGINE
# βββββββββββββββββββββββββββββββββββββββββββββββ
DEFAULT_SETTINGS = {
"profile_save_location": "", # blank = ./profiles/
"auto_backup_before_deploy": True,
"dry_run_by_default": False,
"compact_json": False,
"color_output": True,
"confirm_before_apply": True,
"exclude_sensitive_dotfiles": True,
"auto_name_profiles": False,
"backup_directory": "", # blank = ~/.macdna_backup/
"default_capture_categories": "all", # "all" or comma-separated keys
"security_audit_with_capture": False,
"threat_alert_level": "medium", # low, medium, high
}
SENSITIVE_DOTFILES = {".netrc", ".npmrc", ".pypirc", ".docker/config.json"}
def load_settings():
"""Load settings from disk, merging with defaults for any missing keys."""
settings = dict(DEFAULT_SETTINGS)
if os.path.isfile(SETTINGS_FILE):
try:
with open(SETTINGS_FILE) as f:
saved = json.load(f)
settings.update(saved)
except Exception:
pass
return settings
def save_settings(settings):
"""Write settings to disk."""
with open(SETTINGS_FILE, "w") as f:
json.dump(settings, f, indent=2)
def get_profiles_dir(settings):
"""Return the effective profiles directory."""
custom = settings.get("profile_save_location", "").strip()
return custom if custom else PROFILES_DIR
def get_backup_dir(settings):
"""Return the effective backup directory."""
custom = settings.get("backup_directory", "").strip()
return custom if custom else os.path.expanduser("~/.macdna_backup")
def clear():
os.system("clear")
def banner():
w = 46 # inner width between β walls
top = " β" + "β" * w + "β"
bottom = " β" + "β" * w + "β"
# Build lines with exact padding (emoji = 2 cols in terminal)
l1_text = "𧬠M a c D N A v 3"
l2_text = "Capture - Deploy - Clone Your Mac"
l3_text = "Author: cyberspartan77 | v3.0 | 2026"
# Pad accounting for emoji (2 display cols but 1 char)
pad1 = w - len(l1_text) - 1 # -1 for emoji extra col
pad2 = w - len(l2_text)
pad3 = w - len(l3_text)
line1 = " β" + l1_text.center(w)[:-1] + "β" # trim 1 for emoji
line2 = " β" + l2_text.center(w) + "β"
mid = " β " + "β" * w + "β£"
line3 = " β" + l3_text.center(w) + "β"
print(f"""
{CYAN}{BOLD}{top}
{line1}
{line2}
{mid}
{line3}
{bottom}{RESET}
""")
def divider(title=""):
if title:
print(f"\n {CYAN}{'β'*3} {BOLD}{title} {'β'*(40 - len(title))}{RESET}")
else:
print(f" {DIM}{'β'*48}{RESET}")
def status(icon, msg, detail=""):
d = f" {DIM}{detail}{RESET}" if detail else ""
print(f" {icon} {msg}{d}")
def success(msg, detail=""):
status(f"{GREEN}β{RESET}", msg, detail)
def fail(msg, detail=""):
status(f"{RED}β{RESET}", msg, detail)
def warn(msg, detail=""):
status(f"{YELLOW}!{RESET}", msg, detail)
def info(msg, detail=""):
status(f"{CYAN}i{RESET}", msg, detail)
def spinner_line(msg):
sys.stdout.write(f"\r {YELLOW}β³{RESET} {msg}...")
sys.stdout.flush()
def spinner_done(msg):
print(f"\r {GREEN}β{RESET} {msg} ")
def spinner_fail(msg, err=""):
e = f" β {err}" if err else ""
print(f"\r {RED}β{RESET} {msg}{e} ")
def prompt(msg, default=""):
d = f" [{default}]" if default else ""
try:
val = input(f"\n {CYAN}>{RESET} {msg}{d}: ").strip()
except (EOFError, KeyboardInterrupt):
print()
return ""
return val or default
def pause():
try:
input(f"\n {DIM}Press Enter to continue...{RESET}")
except (EOFError, KeyboardInterrupt):
pass
def show_menu(title, options, show_back=True):
"""Display a numbered menu and return the user's choice (1-based) or 0 for back/quit."""
clear()
banner()
divider(title)
print()
for i, (label, desc) in enumerate(options, 1):
print(f" {BOLD}{CYAN}{i}{RESET} {label}")
if desc:
print(f" {DIM}{desc}{RESET}")
if show_back:
print(f"\n {BOLD}{CYAN}0{RESET} {DIM}{'Back' if show_back else 'Quit'}{RESET}")
print()
choice = prompt("Choose an option")
try:
return int(choice)
except (ValueError, TypeError):
return -1
def show_checklist(title, items, preselect_all=True):
"""
Interactive checklist. User toggles items by number, then confirms.
items: list of (key, label) tuples
Returns list of selected keys.
"""
selected = set(range(len(items))) if preselect_all else set()
while True:
clear()
banner()
divider(title)
print(f" {DIM}Toggle items by number. Press A=all, N=none, Enter=confirm.{RESET}\n")
for i, (key, label) in enumerate(items):
mark = f"{GREEN}[x]{RESET}" if i in selected else f"{DIM}[ ]{RESET}"
print(f" {mark} {BOLD}{i + 1}{RESET} {label}")
print(f"\n {DIM}Selected: {len(selected)}/{len(items)}{RESET}")
choice = prompt("Toggle # / A=all / N=none / Enter=GO")
if choice == "":
break
elif choice.upper() == "A":
selected = set(range(len(items)))
elif choice.upper() == "N":
selected.clear()
else:
try:
nums = [int(x.strip()) - 1 for x in choice.replace(",", " ").split()]
for n in nums:
if 0 <= n < len(items):
selected.symmetric_difference_update({n})
except ValueError:
pass
return [items[i][0] for i in sorted(selected)]
# βββββββββββββββββββββββββββββββββββββββββββββββ
# SHELL HELPERS
# βββββββββββββββββββββββββββββββββββββββββββββββ
def run(cmd, shell=True):
try:
r = subprocess.run(cmd, shell=shell, capture_output=True, text=True, timeout=30)
return r.stdout.strip()
except Exception:
return ""
def defaults_read(domain, key=None):
cmd = f"defaults read {domain}" + (f" {key}" if key else "")
return run(cmd)
def defaults_write(domain, key, value, vtype=None):
type_flag = f"-{vtype}" if vtype else ""
cmd = f"defaults write {domain} {key} {type_flag} {value}"
return run(cmd)
# βββββββββββββββββββββββββββββββββββββββββββββββ
# CAPTURE MODULES
# βββββββββββββββββββββββββββββββββββββββββββββββ
def capture_meta():
return {
"captured_at": datetime.datetime.now().isoformat(),
"hostname": run("scutil --get ComputerName"),
"local_hostname": run("scutil --get LocalHostName"),
"macos_version": platform.mac_ver()[0],
"build": run("sw_vers -buildVersion"),
"chip": run("uname -m"),
"serial": run("system_profiler SPHardwareDataType | awk '/Serial Number/{print $NF}'"),
}
def capture_system():
return {
"appearance": {
"dark_mode": defaults_read("NSGlobalDomain", "AppleInterfaceStyle") == "Dark",
"accent_color": defaults_read("NSGlobalDomain", "AppleAccentColor"),
"highlight_color": defaults_read("NSGlobalDomain", "AppleHighlightColor"),
"sidebar_icon_size": defaults_read("NSGlobalDomain", "NSTableViewDefaultSizeMode"),
"reduce_motion": defaults_read("com.apple.universalaccess", "reduceMotion"),
},
"finder": {
"show_extensions": defaults_read("NSGlobalDomain", "AppleShowAllExtensions"),
"show_hidden_files": defaults_read("com.apple.finder", "AppleShowAllFiles"),
"show_path_bar": defaults_read("com.apple.finder", "ShowPathbar"),
"show_status_bar": defaults_read("com.apple.finder", "ShowStatusBar"),
"default_view": defaults_read("com.apple.finder", "FXPreferredViewStyle"),
"new_window_target": defaults_read("com.apple.finder", "NewWindowTarget"),
"search_scope": defaults_read("com.apple.finder", "FXDefaultSearchScope"),
},
"trackpad": {
"tap_to_click": defaults_read("com.apple.AppleMultitouchTrackpad", "Clicking"),
"tracking_speed": defaults_read("NSGlobalDomain", "com.apple.trackpad.scaling"),
"natural_scrolling": defaults_read("NSGlobalDomain", "com.apple.swipescrolldirection"),
},
"mouse": {
"tracking_speed": defaults_read("NSGlobalDomain", "com.apple.mouse.scaling"),
},
"sounds": {
"ui_sounds": defaults_read("NSGlobalDomain", "com.apple.sound.uiaudio.enabled"),
},
"screenshots": {
"location": defaults_read("com.apple.screencapture", "location"),
"format": defaults_read("com.apple.screencapture", "type"),
"disable_shadow": defaults_read("com.apple.screencapture", "disable-shadow"),
},
"timezone": run("systemsetup -gettimezone 2>/dev/null | awk -F': ' '{print $2}'"),
}
def capture_dock():
dock_plist = os.path.expanduser("~/Library/Preferences/com.apple.dock.plist")
apps = []
try:
with open(dock_plist, "rb") as f:
dock_data = plistlib.load(f)
for item in dock_data.get("persistent-apps", []):
tile = item.get("tile-data", {})
label = tile.get("file-label", "")
path = tile.get("file-data", {}).get("_CFURLString", "")
if label:
apps.append({"label": label, "path": path})
except Exception:
pass
return {
"apps": apps,
"position": defaults_read("com.apple.dock", "orientation"),
"tile_size": defaults_read("com.apple.dock", "tilesize"),
"autohide": defaults_read("com.apple.dock", "autohide"),
"magnification": defaults_read("com.apple.dock", "magnification"),
"minimize_effect": defaults_read("com.apple.dock", "mineffect"),
"show_recents": defaults_read("com.apple.dock", "show-recents"),
}
def capture_apps():
brew_formulae = run("brew list --formula 2>/dev/null").splitlines() if shutil.which("brew") else []
brew_casks = run("brew list --cask 2>/dev/null").splitlines() if shutil.which("brew") else []
mas_apps = []
if shutil.which("mas"):
for line in run("mas list 2>/dev/null").splitlines():
parts = line.split(None, 1)
if len(parts) == 2:
mas_apps.append({"id": parts[0], "name": parts[1].split("(")[0].strip()})
all_apps = []
for app_dir in ["/Applications", os.path.expanduser("~/Applications")]:
if os.path.isdir(app_dir):
for item in os.listdir(app_dir):
if item.endswith(".app"):
all_apps.append(item.replace(".app", ""))
return {
"homebrew": {"formulae": brew_formulae, "casks": brew_casks},
"mas": mas_apps,
"all_installed": sorted(set(all_apps)),
}
def capture_keyboard():
return {
"key_repeat": defaults_read("NSGlobalDomain", "KeyRepeat"),
"initial_key_repeat": defaults_read("NSGlobalDomain", "InitialKeyRepeat"),
"press_and_hold": defaults_read("NSGlobalDomain", "ApplePressAndHoldEnabled"),
"fn_key_behavior": defaults_read("NSGlobalDomain", "com.apple.keyboard.fnState"),
"auto_correct": defaults_read("NSGlobalDomain", "NSAutomaticSpellingCorrectionEnabled"),
"auto_capitalize": defaults_read("NSGlobalDomain", "NSAutomaticCapitalizationEnabled"),
"smart_quotes": defaults_read("NSGlobalDomain", "NSAutomaticQuoteSubstitutionEnabled"),
"smart_dashes": defaults_read("NSGlobalDomain", "NSAutomaticDashSubstitutionEnabled"),
"hot_corners": {
"top_left": defaults_read("com.apple.dock", "wvous-tl-corner"),
"top_right": defaults_read("com.apple.dock", "wvous-tr-corner"),
"bottom_left": defaults_read("com.apple.dock", "wvous-bl-corner"),
"bottom_right": defaults_read("com.apple.dock", "wvous-br-corner"),
},
}
def capture_security():
return {
"filevault": "On" in run("fdesetup status 2>/dev/null"),
"firewall": defaults_read("/Library/Preferences/com.apple.alf", "globalstate"),
"gatekeeper": "enabled" in run("spctl --status 2>/dev/null").lower(),
"sip": "enabled" in run("csrutil status 2>/dev/null").lower(),
"screen_lock": {
"require_password": defaults_read("com.apple.screensaver", "askForPassword"),
"delay_seconds": defaults_read("com.apple.screensaver", "askForPasswordDelay"),
},
}
def capture_shell():
home = Path.home()
dotfiles = {}
for name in [".zshrc", ".bashrc", ".zprofile", ".bash_profile", ".aliases",
".exports", ".functions", ".gitconfig", ".vimrc", ".tmux.conf"]:
path = home / name
if path.is_file():
try:
dotfiles[name] = path.read_text(errors="replace")
except Exception:
dotfiles[name] = f"[error reading {name}]"
return {
"default_shell": run("echo $SHELL"),
"path": run("echo $PATH"),
"oh_my_zsh": (home / ".oh-my-zsh").is_dir(),
"prezto": (home / ".zprezto").is_dir(),
"starship": shutil.which("starship") is not None,
"dotfiles": dotfiles,
}
def capture_login_items():
items = []
raw = run('osascript -e \'tell application "System Events" to get the name of every login item\'')
if raw:
items = [i.strip() for i in raw.split(",")]
agents = []
agent_dir = os.path.expanduser("~/Library/LaunchAgents")
if os.path.isdir(agent_dir):
agents = [f for f in os.listdir(agent_dir) if f.endswith(".plist")]
return {"login_items": items, "launch_agents": agents}
def capture_fonts():
user_fonts = []
font_dir = os.path.expanduser("~/Library/Fonts")
if os.path.isdir(font_dir):
user_fonts = sorted(os.listdir(font_dir))
return {"user_fonts": user_fonts}
def capture_network():
dns = run("scutil --dns | grep 'nameserver\\[' | awk '{print $3}' | sort -u").splitlines()
custom_hosts = []
try:
with open("/etc/hosts") as f:
for line in f:
line = line.strip()
if line and not line.startswith("#") and "localhost" not in line.lower():
custom_hosts.append(line)
except Exception:
pass
return {
"dns_servers": dns,
"custom_hosts": custom_hosts,
"wifi_network": run("/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I 2>/dev/null | awk '/ SSID/{print $2}'"),
}
# All capture modules
CAPTURE_MODULES = [
("meta", "Machine Identity", capture_meta),
("system", "System Preferences", capture_system),
("dock", "Dock Layout", capture_dock),
("apps", "Applications", capture_apps),
("keyboard", "Keyboard & Input", capture_keyboard),
("security", "Security", capture_security),
("shell", "Shell & Dotfiles", capture_shell),
("login_items", "Login Items", capture_login_items),
("fonts", "Fonts", capture_fonts),
("network", "Network", capture_network),
]
# βββββββββββββββββββββββββββββββββββββββββββββββ
# DEPLOY MODULES
# βββββββββββββββββββββββββββββββββββββββββββββββ
def deploy_system(data, dry_run=False):
results = []
appearance = data.get("appearance", {})
finder = data.get("finder", {})
trackpad = data.get("trackpad", {})
screenshots = data.get("screenshots", {})
actions = []
if appearance.get("dark_mode"):
actions.append(("Dark Mode ON", 'osascript -e \'tell app "System Events" to tell appearance preferences to set dark mode to true\''))
else:
actions.append(("Dark Mode OFF", 'osascript -e \'tell app "System Events" to tell appearance preferences to set dark mode to false\''))
if appearance.get("accent_color"):
actions.append((f"Accent color -> {appearance['accent_color']}", f"defaults write NSGlobalDomain AppleAccentColor -int {appearance['accent_color']}"))
if finder.get("show_extensions"):
actions.append(("Show file extensions", "defaults write NSGlobalDomain AppleShowAllExtensions -bool true"))
if finder.get("show_hidden_files"):
actions.append(("Show hidden files", "defaults write com.apple.finder AppleShowAllFiles -bool true"))
if finder.get("show_path_bar"):
actions.append(("Show Finder path bar", "defaults write com.apple.finder ShowPathbar -bool true"))
if finder.get("show_status_bar"):
actions.append(("Show Finder status bar", "defaults write com.apple.finder ShowStatusBar -bool true"))
if trackpad.get("tap_to_click") == "1":
actions.append(("Tap to click ON", "defaults write com.apple.AppleMultitouchTrackpad Clicking -bool true"))
if screenshots.get("location"):
actions.append((f"Screenshots -> {screenshots['location']}", f"defaults write com.apple.screencapture location -string \"{screenshots['location']}\""))
if screenshots.get("format"):
actions.append((f"Screenshot format -> {screenshots['format']}", f"defaults write com.apple.screencapture type -string {screenshots['format']}"))
for label, cmd in actions:
if dry_run:
info(label, "[DRY RUN]")
else:
run(cmd)
success(label)
results.append(label)
return results
def deploy_dock(data, dry_run=False):
results = []
pairs = [
("tile_size", "com.apple.dock", "tilesize", "int"),
("autohide", "com.apple.dock", "autohide", "bool"),
("show_recents", "com.apple.dock", "show-recents", "bool"),
]
for key, domain, pref, vtype in pairs:
val = data.get(key)
if val:
label = f"{pref} -> {val}"
if dry_run:
info(label, "[DRY RUN]")
else:
defaults_write(domain, pref, val, vtype)
success(label)
results.append(label)
pos = data.get("position")
if pos:
label = f"Dock position -> {pos}"
if dry_run:
info(label, "[DRY RUN]")
else:
defaults_write("com.apple.dock", "orientation", f'"{pos}"')
success(label)
results.append(label)
if not dry_run:
run("killall Dock 2>/dev/null")
info("Dock restarted")
return results
def deploy_apps(data, dry_run=False):
results = []
brew = data.get("homebrew", {})
formulae = brew.get("formulae", [])
casks = brew.get("casks", [])
mas_apps = data.get("mas", [])
if not shutil.which("brew"):
warn("Homebrew not installed β skipping app installs")
return results
if formulae:
installed = set(run("brew list --formula").splitlines())
to_install = [f for f in formulae if f not in installed]
if to_install:
label = f"{len(to_install)} brew formulae"
if dry_run:
info(label, "[DRY RUN]")
for f in to_install:
print(f" {DIM}{f}{RESET}")
else:
info(f"Installing {label}...")
run(f"brew install {' '.join(to_install)}")
success(label)
results.append(label)
else:
success(f"All {len(formulae)} formulae already installed")
if casks:
installed = set(run("brew list --cask").splitlines())
to_install = [c for c in casks if c not in installed]
if to_install:
label = f"{len(to_install)} brew casks"
if dry_run:
info(label, "[DRY RUN]")
for c in to_install:
print(f" {DIM}{c}{RESET}")
else:
info(f"Installing {label}...")
run(f"brew install --cask {' '.join(to_install)}")
success(label)
results.append(label)
else:
success(f"All {len(casks)} casks already installed")
if mas_apps and shutil.which("mas"):
for app in mas_apps:
label = f"{app['name']} (App Store #{app['id']})"
if dry_run:
info(label, "[DRY RUN]")
else:
run(f"mas install {app['id']}")
success(label)
results.append(label)
return results
def deploy_keyboard(data, dry_run=False):
results = []
settings = {
"key_repeat": ("NSGlobalDomain", "KeyRepeat", "int"),
"initial_key_repeat": ("NSGlobalDomain", "InitialKeyRepeat", "int"),
"press_and_hold": ("NSGlobalDomain", "ApplePressAndHoldEnabled", "bool"),
"fn_key_behavior": ("NSGlobalDomain", "com.apple.keyboard.fnState", "bool"),
"auto_correct": ("NSGlobalDomain", "NSAutomaticSpellingCorrectionEnabled", "bool"),
"auto_capitalize": ("NSGlobalDomain", "NSAutomaticCapitalizationEnabled", "bool"),
"smart_quotes": ("NSGlobalDomain", "NSAutomaticQuoteSubstitutionEnabled", "bool"),
"smart_dashes": ("NSGlobalDomain", "NSAutomaticDashSubstitutionEnabled", "bool"),
}
for key, (domain, pref, vtype) in settings.items():
val = data.get(key)
if val:
label = f"{pref} -> {val}"
if dry_run:
info(label, "[DRY RUN]")
else:
defaults_write(domain, pref, val, vtype)
success(label)
results.append(label)
hc = data.get("hot_corners", {})
for corner, pref in [("top_left", "wvous-tl-corner"), ("top_right", "wvous-tr-corner"),
("bottom_left", "wvous-bl-corner"), ("bottom_right", "wvous-br-corner")]:
val = hc.get(corner)
if val:
label = f"Hot corner {corner} -> {val}"
if dry_run:
info(label, "[DRY RUN]")
else:
defaults_write("com.apple.dock", pref, val, "int")
success(label)
results.append(label)
return results
def deploy_security(data, dry_run=False):
results = []
lock = data.get("screen_lock", {})
if lock.get("require_password"):
label = "Require password after sleep"
if dry_run:
info(label, "[DRY RUN]")
else:
defaults_write("com.apple.screensaver", "askForPassword", "1", "int")
success(label)
results.append(label)
if lock.get("delay_seconds"):
label = f"Password delay -> {lock['delay_seconds']}s"
if dry_run:
info(label, "[DRY RUN]")
else:
defaults_write("com.apple.screensaver", "askForPasswordDelay", lock["delay_seconds"], "int")
success(label)
results.append(label)
if data.get("filevault"):
warn("FileVault was ON β enable manually in System Settings")
if data.get("firewall"):
warn(f"Firewall was state={data['firewall']} β enable via System Settings or socketfilterfw")
return results
def deploy_shell(data, dry_run=False):
results = []
settings = load_settings()
home = Path.home()
dotfiles = data.get("dotfiles", {})
if not dotfiles:
info("No dotfiles in profile")
return results
do_backup = settings.get("auto_backup_before_deploy", True)
bdir = get_backup_dir(settings)
backup_dir = Path(bdir) / datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
for name, content in dotfiles.items():
target = home / name
label = f"Restore {name}"
if dry_run:
exists = " (would backup existing)" if target.exists() else ""
info(f"{label}{exists}", "[DRY RUN]")
else:
if target.exists() and do_backup:
backup_dir.mkdir(parents=True, exist_ok=True)
shutil.copy2(target, backup_dir / name)
info(f"Backed up {name}")
target.write_text(content)
success(label)
results.append(label)
if not dry_run and do_backup and backup_dir.exists():
info(f"Backups -> {backup_dir}")
return results
DEPLOY_MODULES = [
("system", "System Preferences", deploy_system),
("dock", "Dock Layout", deploy_dock),
("apps", "Applications", deploy_apps),
("keyboard", "Keyboard & Input", deploy_keyboard),
("security", "Security", deploy_security),
("shell", "Shell & Dotfiles", deploy_shell),
]
# βββββββββββββββββββββββββββββββββββββββββββββββ
# HTML REPORT GENERATOR
# βββββββββββββββββββββββββββββββββββββββββββββββ
def generate_html_report(profile, filepath):
"""Generate an interactive HTML viewer for the captured profile."""
meta = profile.get("meta", {})
hostname = meta.get("hostname", "Unknown Mac")
captured = meta.get("captured_at", "")
macos_ver = meta.get("macos_version", "")
chip = meta.get("chip", "")
# Section icons and friendly names
section_map = {
"meta": ("π»", "Machine Identity"),
"system": ("βοΈ", "System Preferences"),
"dock": ("π", "Dock Layout"),
"apps": ("π¦", "Applications"),
"keyboard": ("β¨οΈ", "Keyboard & Input"),
"security": ("π", "Security"),
"shell": ("π", "Shell & Dotfiles"),
"login_items": ("π", "Login Items"),
"fonts": ("π€", "Fonts"),
"network": ("π", "Network"),
}
# Build section cards
section_cards = ""
for key in ["meta", "system", "dock", "apps", "keyboard", "security", "shell", "login_items", "fonts", "network"]:
data = profile.get(key)
if not data:
continue
icon, title = section_map.get(key, ("π", key.title()))
section_cards += _build_section_card(key, icon, title, data)
# Stats for header
n_apps = len(profile.get("apps", {}).get("all_installed", []))
n_brew = len(profile.get("apps", {}).get("homebrew", {}).get("formulae", []))
n_casks = len(profile.get("apps", {}).get("homebrew", {}).get("casks", []))
n_dock = len(profile.get("dock", {}).get("apps", []))
n_dots = len(profile.get("shell", {}).get("dotfiles", {}))
n_fonts = len(profile.get("fonts", {}).get("user_fonts", []))
dark = profile.get("system", {}).get("appearance", {}).get("dark_mode", False)
profile_json_escaped = json.dumps(profile, indent=2, default=str).replace("</", "<\\/").replace("'", "\\'")
html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>𧬠MacDNA β {hostname}</title>
<style>
:root {{
--bg: #0d1117;
--card: #161b22;
--border: #30363d;
--text: #e6edf3;
--dim: #8b949e;
--cyan: #58a6ff;
--green: #3fb950;
--yellow: #d29922;
--red: #f85149;
--purple: #bc8cff;
--font: -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Segoe UI', sans-serif;
--mono: 'SF Mono', 'Menlo', 'Monaco', 'Consolas', monospace;
}}
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{
font-family: var(--font);
background: var(--bg);
color: var(--text);
line-height: 1.6;
padding: 0;
}}
/* Header */
.header {{
background: linear-gradient(135deg, #161b22 0%, #1a2332 100%);
border-bottom: 1px solid var(--border);
padding: 2rem 2rem 1.5rem;
text-align: center;
}}
.header h1 {{
font-size: 2rem;
font-weight: 700;
margin-bottom: 0.25rem;
}}
.header h1 span {{ color: var(--cyan); }}
.header .subtitle {{
color: var(--dim);
font-size: 0.95rem;
}}
.header .meta-row {{
display: flex;
justify-content: center;
gap: 2rem;
margin-top: 1rem;
flex-wrap: wrap;
}}
.header .meta-item {{
font-size: 0.85rem;
color: var(--dim);
}}
.header .meta-item strong {{
color: var(--text);
}}
/* Stats bar */
.stats {{
display: flex;
justify-content: center;
gap: 1.5rem;
padding: 1rem 2rem;
background: var(--card);
border-bottom: 1px solid var(--border);
flex-wrap: wrap;
}}
.stat {{
text-align: center;
min-width: 80px;
}}
.stat .num {{
font-size: 1.5rem;
font-weight: 700;
color: var(--cyan);
}}
.stat .label {{
font-size: 0.75rem;
color: var(--dim);
text-transform: uppercase;
letter-spacing: 0.5px;
}}
/* Search */
.search-bar {{
padding: 1rem 2rem;
background: var(--bg);
position: sticky;
top: 0;
z-index: 10;
border-bottom: 1px solid var(--border);
}}
.search-bar input {{
width: 100%;
max-width: 500px;
display: block;
margin: 0 auto;
padding: 0.6rem 1rem;
border-radius: 8px;
border: 1px solid var(--border);
background: var(--card);
color: var(--text);
font-size: 0.95rem;
font-family: var(--font);
outline: none;
}}
.search-bar input:focus {{
border-color: var(--cyan);
box-shadow: 0 0 0 2px rgba(88,166,255,0.2);
}}
/* Main content */
.container {{
max-width: 900px;
margin: 0 auto;
padding: 1.5rem;
}}
/* Section cards */
.section {{
background: var(--card);
border: 1px solid var(--border);
border-radius: 10px;
margin-bottom: 1rem;
overflow: hidden;
transition: border-color 0.2s;
}}
.section:hover {{
border-color: var(--cyan);
}}
.section-header {{
display: flex;
align-items: center;
padding: 0.9rem 1.2rem;
cursor: pointer;
user-select: none;
gap: 0.75rem;
background: transparent;
transition: background 0.15s;
}}
.section-header:hover {{
background: rgba(88,166,255,0.05);
}}
.section-icon {{
font-size: 1.3rem;
width: 2rem;
text-align: center;
flex-shrink: 0;
}}
.section-title {{
font-weight: 600;
font-size: 1rem;
flex: 1;
}}
.section-badge {{
font-size: 0.75rem;
padding: 0.15rem 0.6rem;
border-radius: 10px;
background: rgba(88,166,255,0.15);
color: var(--cyan);
font-weight: 500;
}}
.section-arrow {{
color: var(--dim);
transition: transform 0.2s;
font-size: 0.8rem;
}}
.section.open .section-arrow {{
transform: rotate(90deg);
}}
.section-body {{
display: none;
padding: 0 1.2rem 1.2rem;
border-top: 1px solid var(--border);
}}
.section.open .section-body {{
display: block;
padding-top: 1rem;
}}
/* Data tables */
.data-table {{
width: 100%;
border-collapse: collapse;
}}
.data-table tr {{
border-bottom: 1px solid rgba(48,54,61,0.5);
}}
.data-table tr:last-child {{
border-bottom: none;
}}
.data-table td {{
padding: 0.45rem 0;
vertical-align: top;
}}
.data-table td:first-child {{
color: var(--dim);
font-size: 0.85rem;
width: 40%;
padding-right: 1rem;
}}
.data-table td:last-child {{
font-family: var(--mono);
font-size: 0.85rem;
word-break: break-word;
}}
/* Value styling */
.val-true {{ color: var(--green); }}
.val-false {{ color: var(--red); }}
.val-empty {{ color: var(--dim); font-style: italic; }}
.val-string {{ color: var(--text); }}