xdotter 0.2.0

A simple dotfile manager - single binary, no dependencies
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
#!/usr/bin/env python3
"""
xdotter - A simple dotfile manager
Single-file, no dependencies, easy to distribute

Usage:
    xd [COMMAND] [OPTIONS]

Commands:
    deploy              Deploy dotfiles (default)
    undeploy            Remove deployed dotfiles
    check-permissions   Check/fix permissions for deployed files
    validate            Validate configuration file syntax
    completion          Generate shell completion scripts
    new                 Create a new xdotter.toml template
    help                Print this help message
    version             Print version

Options:
    -v, --verbose           Show more information
    -q, --quiet             Do not print any output
    -n, --dry-run           Show what would be done without making changes
    -i, --interactive       Ask for confirmation when unsure
    -f, --force             Force overwrite existing files
    --check-permissions     Check permissions for sensitive files
    --fix-permissions       Fix permissions for sensitive files (implies --check-permissions)
    --no-validate           Skip config syntax validation during deploy

Note:
    Shell completion uses vendored argcomplete for automatic generation
    from argparse definition (no manual maintenance required).

Requires: Python 3.8+
"""

import os
import sys
import stat
import json

# Python version check
if sys.version_info < (3, 8):
    print("Error: Python 3.8+ is required", file=sys.stderr)
    sys.exit(1)

import argparse
from pathlib import Path
from typing import Dict, List, Optional, Tuple

from _vendor.tomli import loads, TOMLDecodeError
# Vendored argcomplete for shell completion (optional, for development)
# try:
#     from _vendor.argcomplete import autocomplete
#     HAS_ARGCOMPLETE = True
# except ImportError:
#     HAS_ARGCOMPLETE = False


# ANSI color codes for output
# Yellow for warnings, Red for errors/risks
COLOR_YELLOW = "\033[1;33m"  # Bold yellow
COLOR_RED = "\033[0;31m"     # Red
COLOR_GREEN = "\033[0;32m"   # Green
COLOR_RESET = "\033[0m"      # Reset to default


# Common error suggestions for TOML
TOML_SUGGESTIONS = {
    "Invalid initial character": "TOML 键名不能以特殊字符开头,请用引号包裹",
    "Expected '=' after a key": "TOML 键值对需要使用 = 连接",
    "Unclosed string": "字符串未闭合,请检查引号是否配对",
    "Invalid number": "数字格式错误,检查是否有前导零或非法字符",
    "Invalid value": "无效的值,TOML 支持:字符串、数字、布尔值、日期、数组、表格",
    "Key appears more than once": "键名重复,TOML 不允许重复键名",
    "Unquoted string": "字符串必须用引号包裹(双引号或单引号)",
    "Expected ']' at the end": "表格标题未闭合,缺少 ]",
    "Invalid control character": "不支持控制字符,使用转义序列(如 \\n, \\t)",
}

# Common error suggestions for JSON
JSON_SUGGESTIONS = {
    "Expecting ',' delimiter": "JSON 对象属性之间需要用逗号分隔",
    "Expecting property name": "JSON 键名必须是字符串(用双引号包裹)",
    "Expecting ':' delimiter": "JSON 键值对需要使用冒号分隔",
    "Expecting value": "JSON 值必须是:字符串、数字、布尔值、null、数组或对象",
    "Unterminated string": "字符串未闭合,检查引号是否配对",
    "Invalid control character": "JSON 不支持控制字符,使用转义序列(如 \\n)",
    "Extra data": "JSON 文件只能包含一个顶层值(对象或数组)",
    "Invalid \\escape": "无效的转义序列,JSON 支持:\\\" \\\\ \\/ \\b \\f \\n \\r \\t \\uXXXX",
}


def detect_config_format(filepath: Path) -> Optional[str]:
    """
    Detect configuration file format based on extension.
    
    Args:
        filepath: Path to the configuration file
        
    Returns:
        'toml', 'json', or None if unknown
    """
    suffix = filepath.suffix.lower()
    if suffix == '.toml':
        return 'toml'
    elif suffix == '.json':
        return 'json'
    return None


def get_toml_suggestion(error: TOMLDecodeError) -> Optional[str]:
    """Get suggestion for fixing TOML error"""
    error_msg = str(error).lower()
    for key, suggestion in TOML_SUGGESTIONS.items():
        if key.lower() in error_msg:
            return suggestion
    return None


def get_json_suggestion(error: json.JSONDecodeError) -> Optional[str]:
    """Get suggestion for fixing JSON error"""
    error_msg = error.msg.lower()
    for key, suggestion in JSON_SUGGESTIONS.items():
        if key.lower() in error_msg:
            return suggestion
    return None


def format_toml_error(filepath: Path, content: str, error: TOMLDecodeError) -> str:
    """
    Format TOML error message with context.
    
    Args:
        filepath: Path to the file
        content: File content
        error: TomlDecodeError exception
        
    Returns:
        Formatted error message string
    """
    line = getattr(error, 'lineno', 1)
    col = getattr(error, 'pos', 1)
    
    # Calculate column from position if pos is absolute
    if hasattr(error, 'pos') and error.pos and line > 1:
        lines = content.splitlines()
        if line <= len(lines):
            # Find column by counting characters in the error line
            try:
                line_start = sum(len(lines[i]) + 1 for i in range(line - 1))
                col = error.pos - line_start + 1
            except (IndexError, TypeError):
                col = 1
    
    lines = content.splitlines()
    error_line = lines[line - 1] if line <= len(lines) else ""
    prev_line = lines[line - 2] if line > 1 else ""
    next_line = lines[line] if line < len(lines) else ""
    
    # Build error message
    msg = [
        f"{COLOR_RED}❌ TOML 语法错误{COLOR_RESET}",
        f"",
        f"文件:{filepath}",
        f"错误:{error.msg} (第 {line} 行,第 {col} 列)",
        f"",
        f"{line} 行:",
    ]
    
    if prev_line:
        msg.append(f"  {line-1} | {prev_line}")
    msg.append(f"{COLOR_RED}> {line} | {error_line}{COLOR_RESET}")
    msg.append(f"    | {' ' * (col-1)}^")
    if next_line:
        msg.append(f"  {line+1} | {next_line}")
    
    # Add suggestion
    suggestion = get_toml_suggestion(error)
    if suggestion:
        msg.append(f"")
        msg.append(f"{COLOR_YELLOW}提示:{suggestion}{COLOR_RESET}")
    
    return "\n".join(msg)


def format_json_error(filepath: Path, content: str, error: json.JSONDecodeError) -> str:
    """
    Format JSON error message with context.
    
    Args:
        filepath: Path to the file
        content: File content
        error: JSONDecodeError exception
        
    Returns:
        Formatted error message string
    """
    line = error.lineno
    col = error.colno
    
    lines = content.splitlines()
    error_line = lines[line - 1] if line <= len(lines) else ""
    prev_line = lines[line - 2] if line > 1 else ""
    next_line = lines[line] if line < len(lines) else ""
    
    # Build error message
    msg = [
        f"{COLOR_RED}❌ JSON 语法错误{COLOR_RESET}",
        f"",
        f"文件:{filepath}",
        f"错误:{error.msg} (第 {line} 行,第 {col} 列)",
        f"",
        f"{line} 行:",
    ]
    
    if prev_line:
        msg.append(f"  {line-1} | {prev_line}")
    msg.append(f"{COLOR_RED}> {line} | {error_line}{COLOR_RESET}")
    msg.append(f"    | {' ' * (col-1)}^")
    if next_line:
        msg.append(f"  {line+1} | {next_line}")
    
    # Add suggestion
    suggestion = get_json_suggestion(error)
    if suggestion:
        msg.append(f"")
        msg.append(f"{COLOR_YELLOW}提示:{suggestion}{COLOR_RESET}")
    
    return "\n".join(msg)


def validate_config(filepath: Path) -> Tuple[bool, str]:
    """
    Validate configuration file syntax.
    
    Args:
        filepath: Path to the configuration file
        
    Returns:
        Tuple of (is_valid, message)
    """
    if not filepath.exists():
        return False, f"File not found: {filepath}"
    
    # Detect format
    fmt = detect_config_format(filepath)
    if fmt is None:
        return False, f"Unknown file format: {filepath.suffix}"
    
    # Read content
    try:
        content = filepath.read_text(encoding='utf-8')
    except OSError as e:
        return False, f"Cannot read file: {e}"
    
    # Validate based on format
    if fmt == 'toml':
        try:
            loads(content)
            return True, f"TOML syntax is valid"
        except TOMLDecodeError as e:
            msg = format_toml_error(filepath, content, e)
            return False, msg
    elif fmt == 'json':
        try:
            json.loads(content)
            return True, f"JSON syntax is valid"
        except json.JSONDecodeError as e:
            msg = format_json_error(filepath, content, e)
            return False, msg
    
    return False, f"Unsupported format: {fmt}"


def get_version() -> str:
    """Get version from environment variable, git tag, or default."""
    # 1. Check environment variable (set by CI during build)
    env_version = os.environ.get("XD_VERSION")
    if env_version:
        return env_version.lstrip("v")

    # 2. Try to get from git tag (only if running from source directory)
    try:
        import subprocess

        # Determine the git directory (parent of the script or current dir)
        script_path = Path(__file__).parent
        # If running from .pyz, use current working directory instead
        if str(script_path).endswith('.pyz') or not script_path.is_dir():
            git_dir = Path.cwd()
        else:
            git_dir = script_path

        result = subprocess.run(
            ["git", "describe", "--tags", "--exact-match"],
            capture_output=True,
            text=True,
            cwd=git_dir
        )
        if result.returncode == 0:
            return result.stdout.strip().lstrip("v")

        # Try git describe for dev versions
        result = subprocess.run(
            ["git", "describe", "--tags"],
            capture_output=True,
            text=True,
            cwd=git_dir
        )
        if result.returncode == 0:
            return result.stdout.strip().lstrip("v")
    except (FileNotFoundError, subprocess.SubprocessError):
        pass

    # 3. Default version (for development or when git is not available)
    return "0.3.3"


def get_build_info() -> Optional[Dict[str, str]]:
    """
    Get build information if available.
    
    Returns:
        Dict with 'time' and/or 'commit' keys if available, None otherwise.
    """
    info = {}
    
    # 1. Try to import embedded build_info module (for .pyz installations)
    try:
        import build_info
        if hasattr(build_info, 'XD_BUILD_TIME'):
            info['time'] = build_info.XD_BUILD_TIME
        if hasattr(build_info, 'XD_BUILD_COMMIT'):
            info['commit'] = build_info.XD_BUILD_COMMIT
    except ImportError:
        pass
    
    # 2. Check environment variables (for direct Python execution)
    if 'time' not in info:
        env_time = os.environ.get("XD_BUILD_TIME")
        if env_time:
            info['time'] = env_time
    
    if 'commit' not in info:
        env_commit = os.environ.get("XD_BUILD_COMMIT")
        if env_commit:
            info['commit'] = env_commit
    
    # 3. Try to get commit from git (for source installations)
    if 'commit' not in info:
        try:
            import subprocess
            script_path = Path(__file__).parent
            if not str(script_path).endswith('.pyz') and script_path.is_dir():
                result = subprocess.run(
                    ["git", "rev-parse", "--short", "HEAD"],
                    capture_output=True,
                    text=True,
                    cwd=script_path
                )
                if result.returncode == 0 and result.stdout.strip():
                    info['commit'] = result.stdout.strip()
        except (FileNotFoundError, subprocess.SubprocessError):
            pass
    
    return info if info else None


VERSION = get_version()
BUILD_INFO = get_build_info()


# Sensitive paths and their required permissions
# Format: path pattern (with ~ support) -> (required_mode, description)
# Supports glob patterns for filenames
SENSITIVE_PATHS: Dict[str, Tuple[int, str]] = {
    # SSH
    "~/.ssh": (0o700, "SSH directory"),
    "~/.ssh/id_rsa": (0o600, "SSH RSA private key"),
    "~/.ssh/id_ed25519": (0o600, "SSH Ed25519 private key"),
    "~/.ssh/id_ecdsa": (0o600, "SSH ECDSA private key"),
    "~/.ssh/id_dsa": (0o600, "SSH DSA private key"),
    "~/.ssh/authorized_keys": (0o600, "SSH authorized keys"),
    "~/.ssh/authorized_keys2": (0o600, "SSH authorized keys (legacy)"),
    "~/.ssh/config": (0o600, "SSH config"),
    "~/.ssh/known_hosts": (0o644, "SSH known hosts"),
    # GPG
    "~/.gnupg": (0o700, "GPG directory"),
    "~/.gnupg/private-keys-v1.d": (0o700, "GPG private keys directory"),
    "~/.gnupg/pubring.kbx": (0o644, "GPG public keyring"),
    "~/.gnupg/pubring.gpg": (0o644, "GPG public keyring (legacy)"),
    "~/.gnupg/secring.gpg": (0o600, "GPG secret keyring (legacy)"),
    "~/.gnupg/gpg.conf": (0o600, "GPG config"),
    # Shell configs (affect environment variables and PATH)
    "~/.bashrc": (0o644, "Bash config"),
    "~/.zshrc": (0o644, "Zsh config"),
    "~/.bash_profile": (0o644, "Bash login profile"),
    "~/.profile": (0o644, "Shell profile"),
    "~/.zprofile": (0o644, "Zsh login profile"),
    "~/.zshenv": (0o644, "Zsh environment"),
    "~/.zlogin": (0o644, "Zsh login script"),
    "~/.bash_logout": (0o644, "Bash logout script"),
    # X11 / GUI related (affect graphical session and app launching)
    "~/.xinitrc": (0o755, "X11 initialization script"),
    "~/.xsession": (0o755, "X session script"),
    "~/.xprofile": (0o644, "X profile"),
    "~/.Xauthority": (0o600, "X11 authority file"),
    "~/.Xresources": (0o644, "X resources"),
    "~/.Xdefaults": (0o644, "X defaults"),
    # Other sensitive files
    "~/.netrc": (0o600, "Netrc password file"),
    "~/.pgpass": (0o600, "PostgreSQL password file"),
    "~/.my.cnf": (0o600, "MySQL config (may contain passwords)"),
    "~/.pgp/secring.pgp": (0o600, "PGP secret keyring"),
    "~/.config/gnupg": (0o700, "GPG directory (XDG)"),
    "~/.config/gnupg/private-keys-v1.d": (0o700, "GPG private keys directory (XDG)"),
}

# Glob patterns for sensitive files (matched against filename only)
# Format: glob pattern -> (required_mode, description)
SENSITIVE_PATTERNS: List[Tuple[str, int, str]] = [
    # SSH private keys (various names)
    ("id_rsa*", 0o600, "SSH RSA private key"),
    ("id_ed25519*", 0o600, "SSH Ed25519 private key"),
    ("id_ecdsa*", 0o600, "SSH ECDSA private key"),
    ("id_dsa*", 0o600, "SSH DSA private key"),
    ("*_rsa", 0o600, "SSH RSA private key"),
    ("*_ed25519", 0o600, "SSH Ed25519 private key"),
    ("*_ecdsa", 0o600, "SSH ECDSA private key"),
    ("*_dsa", 0o600, "SSH DSA private key"),
    ("*.pem", 0o600, "PEM private key"),
    ("*.key", 0o600, "Private key file"),
    # GPG private keys
    ("*.gpg", 0o600, "GPG file"),
    ("*.asc", 0o600, "ASCII armored key"),
    # Shell config backups (may contain sensitive data)
    ("*.bashrc", 0o644, "Bash config backup"),
    ("*.zshrc", 0o644, "Zsh config backup"),
    ("*.profile", 0o644, "Shell profile backup"),
]


class ConfigParser:
    """TOML parser using embedded tomli for robust parsing"""

    @staticmethod
    def parse(content: str) -> Dict:
        """
        Parse TOML content using tomli.
        
        Args:
            content: TOML content as string
            
        Returns:
            Dictionary with 'links' and 'dependencies' keys
        """
        raw_data = loads(content)
        return {
            "links": raw_data.get("links", {}),
            "dependencies": raw_data.get("dependencies", {})
        }


def get_home_dir() -> Path:
    """Get the user's home directory"""
    home = os.path.expanduser("~")
    return Path(home)


def get_required_permission(path: Path) -> Optional[Tuple[int, str]]:
    """
    Get the required permission for a path based on SENSITIVE_PATHS.

    Args:
        path: The path to check (can be absolute or relative to home)

    Returns:
        Tuple of (required_mode, description) if path matches, None otherwise
    """
    import fnmatch
    
    home = get_home_dir()

    # Normalize path to ~ format for matching
    # Use the original path (don't resolve symlinks) for matching
    try:
        # Expand ~ but don't resolve symlinks
        expanded_path = path.expanduser()
        path_str = str(expanded_path)
        home_str = str(home)

        if path_str.startswith(home_str):
            tilde_path = "~" + path_str[len(home_str):]
        else:
            tilde_path = str(path)
    except (OSError, RuntimeError):
        tilde_path = str(path)

    # 1. Direct match in SENSITIVE_PATHS
    if tilde_path in SENSITIVE_PATHS:
        return SENSITIVE_PATHS[tilde_path]

    # 2. Check filename against SENSITIVE_PATTERNS
    filename = expanded_path.name
    for pattern, mode, desc in SENSITIVE_PATTERNS:
        if fnmatch.fnmatch(filename, pattern):
            return (mode, desc)

    # 3. Check for parent directory matches (for files inside sensitive dirs)
    # Use try/except for is_relative_to (Python 3.9+) compatibility
    for sensitive_path, (mode, desc) in SENSITIVE_PATHS.items():
        sensitive_dir = Path(sensitive_path).expanduser()
        try:
            # Python 3.9+ method
            if hasattr(expanded_path, 'is_relative_to'):
                if expanded_path.is_relative_to(sensitive_dir):
                    return (mode, f"inside {desc}")
            else:
                # Python 3.8 fallback: use resolve() and check prefix
                expanded_resolved = expanded_path.resolve()
                sensitive_resolved = sensitive_dir.resolve()
                try:
                    expanded_resolved.relative_to(sensitive_resolved)
                    return (mode, f"inside {desc}")
                except ValueError:
                    pass
        except (OSError, RuntimeError, ValueError):
            continue

    return None


def check_permission(path: Path, required_mode: int, description: str, args) -> Tuple[bool, str]:
    """
    Check if a path has the correct permission.
    
    Args:
        path: Path to check
        required_mode: Required permission mode (e.g., 0o600)
        description: Description of the path
        args: Command line arguments
    
    Returns:
        Tuple of (is_correct, message)
    """
    try:
        # For symlinks, check the target's permission
        actual_path = path.resolve()
        
        if not actual_path.exists():
            return True, f"Path does not exist: {path}"
        
        current_mode = stat.S_IMODE(actual_path.stat().st_mode)
        
        # Check if current permission is more restrictive or equal
        # We check if any extra bits are set that shouldn't be
        extra_bits = current_mode & ~required_mode
        
        if extra_bits == 0:
            return True, f"{COLOR_GREEN}{COLOR_RESET} {description}: {path} (permission: {current_mode:03o})"
        else:
            return False, f"{COLOR_RED}{COLOR_RESET} {description}: {path} (current: {current_mode:03o}, required: {required_mode:03o})"
            
    except OSError as e:
        return True, f"Cannot check permission for {path}: {e}"


def fix_permission(path: Path, required_mode: int, args) -> Tuple[bool, str]:
    """
    Fix the permission of a path.
    
    Args:
        path: Path to fix
        required_mode: Required permission mode
        args: Command line arguments
    
    Returns:
        Tuple of (success, message)
    """
    try:
        actual_path = path.resolve()
        
        if not actual_path.exists():
            return True, f"Path does not exist: {path}"
        
        if args.dry_run:
            return True, f"Would fix permission for {path} to {required_mode:03o}"
        
        actual_path.chmod(required_mode)
        return True, f"Fixed permission for {path} to {required_mode:03o}"
        
    except OSError as e:
        return False, f"Failed to fix permission for {path}: {e}"


def check_permissions_for_link(actual_path: Path, link: str, args) -> Tuple[bool, List[str]]:
    """
    Check permissions for the source file if the link target is a sensitive path.

    Args:
        actual_path: The source file path (the actual file, not symlink)
        link: The link path (where symlink will be placed)
        args: Command line arguments

    Returns:
        Tuple of (can_deploy, messages)
        can_deploy is False if permission issue found and not forced
    """
    messages = []
    can_deploy = True

    home_dir = get_home_dir()
    link_path = Path(link.replace("~", str(home_dir))).expanduser()

    # Check if this link path is a sensitive path
    perm_info = get_required_permission(link_path)

    if perm_info:
        required_mode, description = perm_info

        # Check the SOURCE file's permission (not the target, which doesn't exist yet)
        is_correct, msg = check_permission(actual_path, required_mode, description, args)
        # Print permission check result directly
        if is_correct:
            log(args, "info", msg)
        else:
            log(args, "warning", msg)
            # Permission issue found
            if not args.force:
                can_deploy = False
                log(args, "error", f"Skipping {link}: permission issue for {description}")
        messages.append(msg)

        # If not correct and fix is requested
        if not is_correct and getattr(args, 'fix_permissions', False):
            success, fix_msg = fix_permission(actual_path, required_mode, args)
            messages.append(fix_msg)
            if success:
                can_deploy = True  # Can deploy after fixing

    return can_deploy, messages


def log(args, level: str, msg: str):
    """Print log message based on verbosity level"""
    if args.quiet:
        return

    if level == "info" and (args.verbose or not args.quiet):
        print(msg)
    elif level == "debug" and args.verbose:
        print(f"[DEBUG] {msg}")
    elif level == "warning":
        print(f"{COLOR_YELLOW}[WARNING] {msg}{COLOR_RESET}")
    elif level == "error":
        print(f"{COLOR_RED}[ERROR] {msg}{COLOR_RESET}", file=sys.stderr)


def detect_circular_symlink_scenario(link_path: Path, actual: Path, args=None) -> Optional[Tuple[Path, Path]]:
    """
    Detect the circular symlink scenario:
    Creating symlink at A/B pointing to C/B, when C is already a symlink to A.

    Scenario:
        C -> A  (C is a symlink to A)
        Creating: A/B -> C/B
        This becomes: A/B -> C/B -> A/B (circular!)

    Args:
        link_path: The path where symlink will be created (A/B)
        actual: The target path the symlink will point to (C/B)
        args: Optional args for debug logging

    Returns:
        Tuple of (problematic_symlink_C, target_A) if detected, None otherwise
    """
    try:
        # We're creating: link_path (A/B) -> actual (C/B)
        # Check if actual's parent (C) is a symlink to link's parent (A)
        link_absolute = link_path.absolute()
        
        # Use actual.parent (not actual.resolve().parent) to get C, not A
        # actual = C/B, actual.parent = C (even if C is a symlink)
        actual_parent = actual.parent  # C
        link_parent = link_absolute.parent  # A

        # Check if actual_parent (C) is a symlink
        if actual_parent.is_symlink():
            try:
                parent_target = Path(os.readlink(actual_parent))
                if not parent_target.is_absolute():
                    parent_target = actual_parent.parent / parent_target
                parent_target_resolved = parent_target.resolve()

                # Check if link_parent (A) equals the symlink target
                if parent_target_resolved == link_parent:
                    if args and args.verbose:
                        log(args, "debug", f"Circular scenario detected: {actual_parent} -> {parent_target_resolved}")
                        log(args, "debug", f"Creating {link_path} -> {actual} would be circular")
                    return (actual_parent, link_parent)  # Return (C, A)
            except (OSError, ValueError):
                pass

        return None
    except (OSError, ValueError, RuntimeError):
        return None


def would_create_symlink_loop(link_path: Path, actual: Path, args=None) -> bool:
    """
    Check if creating a symlink at link_path pointing to actual would create a loop.

    A loop would be created ONLY if:
    - link_path is inside a symlinked directory that points to actual's parent, AND
    - link_path itself would be a symlink pointing to a file inside that same tree

    This is a very specific scenario:
        /home/user/.config -> /home/user/dotfiles/.config (symlink)
        Creating: /home/user/.config/file -> /home/user/dotfiles/.config/file
        This becomes: /home/user/dotfiles/.config/file -> /home/user/dotfiles/.config/file
        Which is a self-referential loop.

    Normal scenarios should NOT trigger this:
        /home/user/.config/helix -> /home/user/dotfiles/helix (symlink dir)
        Creating: /home/user/.config/helix/config.toml -> /home/user/dotfiles/helix/config.toml
        This is fine because the symlink target is the file, not the path through symlink.

    Note: If link_path already exists as a symlink pointing to actual, this is NOT a loop.

    Args:
        link_path: The path where symlink will be created
        actual: The target path the symlink will point to
        args: Optional args for debug logging

    Returns:
        True if creating the symlink would create a loop, False otherwise
    """
    try:
        # If link_path already exists as a symlink to actual, not a loop
        if link_path.is_symlink():
            try:
                existing_target = Path(os.readlink(link_path)).resolve()
                if existing_target == actual.resolve():
                    return False  # Already points to correct target
            except (OSError, ValueError):
                pass

        # Use absolute path for link_path (don't resolve, which would follow symlink)
        link_absolute = link_path.absolute()
        actual_resolved = actual.resolve()

        # Debug logging
        if args and args.verbose:
            log(args, "debug", f"Loop check: {link_absolute} -> {actual_resolved}")

        # Check: is link_path inside a symlinked directory?
        symlink_parent = None
        current = link_absolute.parent
        while current != current.parent:
            if current.is_symlink():
                target = Path(os.readlink(current))
                if not target.is_absolute():
                    target = current.parent / target
                try:
                    target_resolved = target.resolve()
                    symlink_parent = (current, target_resolved)
                    break  # Use the closest symlink parent
                except (OSError, ValueError):
                    pass
            current = current.parent

        # If no symlink parent found, no loop possible
        if symlink_parent is None:
            return False

        symlink_source, symlink_target = symlink_parent

        # Check if actual is inside the symlink target directory
        try:
            actual_resolved.relative_to(symlink_target)
            # actual is inside symlink target - but this alone is NOT a loop!
            
            # A loop occurs ONLY if:
            # link_path (through symlink) would point to itself
            # i.e., the relative path from symlink_source to link_path
            # equals the relative path from symlink_target to actual
            
            # Get relative path from symlink source to link_path
            rel_from_source = link_absolute.relative_to(symlink_source)
            
            # Get relative path from symlink target to actual
            rel_from_target = actual_resolved.relative_to(symlink_target)
            
            # If they're the same, creating the symlink would be self-referential
            if rel_from_source == rel_from_target:
                if args and args.verbose:
                    log(args, "debug", f"  Loop detected: {symlink_source} -> {symlink_target}")
                    log(args, "debug", f"  Relative paths match: {rel_from_source}")
                return True
            
            # Different relative paths = not a loop
            if args and args.verbose:
                log(args, "debug", f"  Not a loop: {rel_from_source} != {rel_from_target}")
            return False
            
        except ValueError:
            # actual is NOT inside symlink target, no loop
            return False

    except (OSError, ValueError, RuntimeError):
        # If we can't determine, assume no loop (conservative)
        return False


def paths_would_conflict(link_path: Path, actual: Path) -> bool:
    """
    Check if link_path and actual would conflict (e.g., one is inside the other).

    This check only returns True if:
    1. link_path is the same as actual
    2. link_path is inside actual's directory tree

    It does NOT return True for normal symlink scenarios where the symlink
    and target are in completely different directories.

    Note: If link_path already exists as a symlink, we don't resolve it
    (to avoid following the symlink to the target).

    Args:
        link_path: The path where symlink will be created
        actual: The target path the symlink will point to

    Returns:
        True if paths would conflict, False otherwise
    """
    try:
        # Only check if link_path's parent exists
        if not link_path.parent.exists():
            return False

        # Don't resolve link_path if it's a symlink (would follow the link)
        # Use absolute() instead of resolve() to get absolute path without following links
        if link_path.exists() and link_path.is_symlink():
            link_absolute = link_path.absolute()
        else:
            link_absolute = link_path.absolute()
        
        actual_resolved = actual.resolve()

        # Don't allow if they're the same (comparing absolute paths)
        if link_absolute == actual_resolved:
            return True

        # Check if link_path is inside actual's directory tree
        # This would be a problem: creating link inside target
        try:
            link_absolute.relative_to(actual_resolved)
            return True  # link_path is inside actual
        except ValueError:
            pass

        return False
    except (OSError, ValueError, RuntimeError):
        return False


def create_symlink(actual_path: str, link: str, args) -> Tuple[bool, Optional[str]]:
    """Create a symlink from link to actual_path"""
    try:
        # Expand and resolve actual path
        actual = Path(actual_path).expanduser().resolve()
        if not actual.exists():
            return False, f"Source path does not exist: {actual}"

        # Expand home directory in link path
        home_dir = get_home_dir()
        link_path = Path(link.replace("~", str(home_dir))).expanduser()

        # Check if parent directory is a symlink
        # If so, creating a file symlink would overwrite the actual file!
        # But we can fix this by removing the parent symlink and creating a real directory
        link_parent = link_path.parent
        if link_parent.is_symlink() and not actual.is_dir():
            try:
                parent_target = Path(os.readlink(link_parent))
                if not parent_target.is_absolute():
                    parent_target = link_parent.parent / parent_target
                parent_target_resolved = parent_target.resolve()

                # Check if actual is inside the parent symlink's target
                try:
                    actual.relative_to(parent_target_resolved)
                    # This means: link_parent -> parent_target, and actual is inside parent_target
                    # Creating link_path (inside link_parent) -> actual would overwrite the source file!
                    
                    # Offer to fix in interactive mode, or auto-fix with --force
                    should_fix = False
                    if args.interactive:
                        log(args, "warning", f"Parent directory {link_parent} is a symlink to {parent_target_resolved}")
                        log(args, "warning", f"Creating symlink at {link_path} would overwrite the actual file at {actual}")
                        print(f"Remove {link_parent} and create real directory? [y/n] ", end="")
                        sys.stdout.flush()
                        response = input().strip().lower()
                        should_fix = response == "y"
                    elif args.dry_run:
                        log(args, "info", f"Would remove symlink {link_parent}")
                        log(args, "info", f"Would create real directory {link_parent}")
                        should_fix = True  # In dry-run, just show what would happen
                    elif args.force:
                        # --force: auto-fix by removing parent symlink
                        log(args, "info", f"Removing parent symlink {link_parent}")
                        link_parent.unlink()
                        log(args, "info", f"Creating real directory {link_parent}")
                        link_parent.mkdir(parents=True, exist_ok=True)
                        should_fix = True
                    else:
                        log(args, "warning", f"Parent directory {link_parent} is a symlink to {parent_target_resolved}")
                        log(args, "warning", f"Creating symlink at {link_path} would OVERWRITE the actual file at {actual}")
                        log(args, "warning", "Use -i to interactively fix or --force to auto-fix")
                        return False, f"Would overwrite actual file (parent is symlink)"

                    if should_fix:
                        # Remove the parent symlink and create real directory
                        if not args.dry_run:
                            log(args, "info", f"Removing symlink {link_parent}")
                            link_parent.unlink()
                            log(args, "info", f"Creating real directory {link_parent}")
                            link_parent.mkdir(parents=True, exist_ok=True)
                        # Continue with normal symlink creation
                    else:
                        if not args.dry_run:
                            return False, f"Would overwrite actual file (parent is symlink)"
                except ValueError:
                    pass  # actual is not inside parent symlink target, normal flow
            except (OSError, ValueError):
                pass  # Can't determine, proceed with normal flow

        # Check if link already exists
        if link_path.exists() or link_path.is_symlink():
            if link_path.is_symlink():
                existing_target = os.readlink(link_path)
                if Path(existing_target).resolve() == actual:
                    log(args, "debug", "Symlink already exists, skipping")
                    return True, None

            # Handle existing file/link
            # Warn if target exists but is not a symlink to this location
            if not link_path.is_symlink():
                log(args, "warning", f"Target exists but is not a symlink: {link_path}")

            if args.interactive:
                print(f"Link {link_path} exists, remove it? [y/n] ", end="")
                sys.stdout.flush()
                response = input().strip().lower()
                should_remove = response == "y"
            elif args.force:
                should_remove = True
            else:
                return False, f"Path exists, use --force or --interactive to overwrite: {link_path}"

            if should_remove:
                if args.dry_run:
                    log(args, "debug", f"Would remove {link_path}")
                else:
                    log(args, "debug", f"Removing {link_path}")
                    if link_path.is_dir() and not link_path.is_symlink():
                        import shutil
                        shutil.rmtree(link_path)
                    else:
                        link_path.unlink()
            else:
                log(args, "debug", "Skipping existing link")
                return True, None

        # Check for path conflict (one inside the other)
        if paths_would_conflict(link_path, actual):
            log(args, "warning", f"Path conflict: {link_path} and {actual} would conflict!")
            log(args, "warning", "Skipping this link to prevent issues")
            return False, f"Path conflict detected"

        # Check for symlink loop in specific scenario:
        # If link_path's parent is a symlink pointing near actual
        if would_create_symlink_loop(link_path, actual, args):
            log(args, "warning", f"Creating symlink {link_path} -> {actual} would create a loop!")
            log(args, "warning", "Skipping this link to prevent infinite loop")

            # For directories, ask if user wants to create real directory instead
            if actual.is_dir() and args.interactive:
                print(f"Create real directory at {link_path} instead? [y/n] ", end="")
                sys.stdout.flush()
                response = input().strip().lower()
                if response == "y":
                    if args.dry_run:
                        log(args, "debug", f"Would create directory {link_path}")
                    else:
                        log(args, "debug", f"Creating directory {link_path}")
                        link_path.mkdir(parents=True, exist_ok=True)
                    return True, None

            return False, f"Symlink loop detected, skipped"

        # Check for circular symlink scenario:
        # Creating symlink at A/B pointing to C/B, when C is already a symlink to A
        # This would create: A/B -> C/B -> A/B (circular!)
        circular_result = detect_circular_symlink_scenario(link_path, actual, args)
        if circular_result:
            circular_symlink, link_parent = circular_result
            log(args, "warning", f"Circular symlink scenario detected!")
            log(args, "warning", f"Creating {link_path} -> {actual} when {circular_symlink} -> {link_parent}")
            log(args, "warning", "This would create a circular reference")

            # Handle the circular scenario
            should_fix = False

            # Only ask in interactive mode
            if args.interactive:
                print(f"Remove {circular_symlink} and create real directory? [y/n] ", end="")
                sys.stdout.flush()
                response = input().strip().lower()
                should_fix = response == "y"
            else:
                # Non-interactive: skip by default
                log(args, "warning", "Skipping this link to prevent circular reference (use -i to fix interactively)")
                return False, f"Circular symlink scenario detected, skipped"

            if should_fix:
                # Remove the problematic symlink C
                if args.dry_run:
                    log(args, "info", f"Would remove symlink {circular_symlink}")
                    log(args, "info", f"Would create real directory {circular_symlink}")
                else:
                    log(args, "info", f"Removing symlink {circular_symlink}")
                    try:
                        circular_symlink.unlink()
                    except OSError as e:
                        log(args, "error", f"Failed to remove {circular_symlink}: {e}")
                        return False, f"Failed to remove circular symlink"

                    log(args, "info", f"Creating real directory {circular_symlink}")
                    try:
                        circular_symlink.mkdir(parents=True, exist_ok=True)
                    except OSError as e:
                        log(args, "error", f"Failed to create directory {circular_symlink}: {e}")
                        return False, f"Failed to create directory"

                # After fixing, the symlink creation can proceed normally
                log(args, "info", f"Circular scenario fixed, proceeding with symlink creation")
            else:
                log(args, "warning", "Skipping this link to prevent circular reference")
                return False, f"Circular symlink scenario detected, skipped"

        # Check permissions BEFORE creating symlink (if enabled)
        # This prevents deploying files with wrong permissions to sensitive locations
        if getattr(args, 'check_permissions', False) or getattr(args, 'fix_permissions', False):
            can_deploy, _ = check_permissions_for_link(actual, link, args)
            if not can_deploy:
                return False, f"Permission issue detected, use --force to override"

        # Create parent directory if needed
        link_dir = link_path.parent
        if not link_dir.exists():
            if args.dry_run:
                log(args, "debug", f"Would create directory {link_dir}")
            else:
                log(args, "debug", f"Creating directory {link_dir}")
                link_dir.mkdir(parents=True, exist_ok=True)

        # Create the symlink
        if args.dry_run:
            log(args, "debug", f"Would create symlink {link_path} -> {actual}")
        else:
            log(args, "debug", f"Creating symlink {link_path} -> {actual}")
            os.symlink(actual, link_path)

        return True, None

    except OSError as e:
        return False, f"OS error: {e}"
    except PermissionError as e:
        return False, f"Permission denied: {e}"


def delete_symlink(link: str, args) -> Tuple[bool, Optional[str]]:
    """Delete a symlink"""
    try:
        home_dir = get_home_dir()
        link_path = Path(link.replace("~", str(home_dir))).expanduser()

        if not link_path.exists():
            log(args, "debug", "Link does not exist, skipping")
            return True, None

        if not link_path.is_symlink():
            log(args, "debug", "Not a symlink, skipping")
            return True, None

        # Confirm removal
        if args.interactive:
            print(f"Remove link {link_path}? [y/n] ", end="")
            sys.stdout.flush()
            response = input().strip().lower()
            if response != "y":
                return True, None

        if args.dry_run:
            log(args, "debug", f"Would remove {link_path}")
        else:
            link_path.unlink()
            log(args, "debug", f"Removed {link_path}")

        return True, None

    except OSError as e:
        return False, f"OS error: {e}"
    except PermissionError as e:
        return False, f"Permission denied: {e}"


def deploy_on(config_file: str, args) -> bool:
    """Deploy dotfiles from a config file"""
    log(args, "debug", f"Deploying from {config_file}")
    
    # Validate config syntax before deploying (unless skipped)
    if not getattr(args, 'no_validate', False):
        config_path = Path(config_file)
        if config_path.exists():
            is_valid, msg = validate_config(config_path)
            if not is_valid:
                log(args, "error", msg)
                log(args, "error", "Deployment aborted due to config syntax errors")
                log(args, "info", "Hint: Run 'xd validate' to check config syntax")
                return False

    try:
        with open(config_file, "r", encoding="utf-8") as f:
            content = f.read()
    except FileNotFoundError:
        log(args, "error", f"Config file not found: '{config_file}'")
        return False
    except PermissionError as e:
        log(args, "error", f"Permission denied reading '{config_file}': {e}")
        return False
    except OSError as e:
        log(args, "error", f"Failed to read config '{config_file}': {e}")
        return False

    try:
        config = ConfigParser.parse(content)
    except Exception as e:
        log(args, "error", f"Failed to parse config: {e}")
        return False

    current_dir = Path.cwd()
    success = True

    # Process links
    for actual_path, link in config.get("links", {}).items():
        log(args, "info", f"deploy: {link} -> {actual_path}")
        ok, error = create_symlink(actual_path, link, args)
        if not ok:
            log(args, "error", f"failed to create link: {error}")
            success = False

    # Process dependencies
    for dep_name, dep_path in config.get("dependencies", {}).items():
        log(args, "debug", f"dependency: {dep_name}, path: {dep_path}")
        dep_dir = current_dir / dep_path

        try:
            os.chdir(dep_dir)
            log(args, "debug", f"entering {dep_dir}")
            dep_config = dep_dir / "xdotter.toml"
            if dep_config.exists():
                if not deploy_on(str(dep_config), args):
                    success = False
        except FileNotFoundError:
            log(args, "error", f"Dependency directory not found: {dep_dir}")
            success = False
        except OSError as e:
            log(args, "error", f"failed to enter {dep_dir}: {e}")
            success = False
        finally:
            os.chdir(current_dir)
            log(args, "debug", f"leaving {dep_dir}")

    return success


def undeploy_on(config_file: str, args) -> bool:
    """Undeploy dotfiles from a config file"""
    log(args, "debug", f"Undeploying from {config_file}")

    try:
        with open(config_file, "r", encoding="utf-8") as f:
            content = f.read()
    except FileNotFoundError:
        log(args, "error", f"Config file not found: '{config_file}'")
        return False
    except PermissionError as e:
        log(args, "error", f"Permission denied reading '{config_file}': {e}")
        return False
    except OSError as e:
        log(args, "error", f"Failed to read config '{config_file}': {e}")
        return False

    try:
        config = ConfigParser.parse(content)
    except Exception as e:
        log(args, "error", f"Failed to parse config: {e}")
        return False

    current_dir = Path.cwd()
    success = True

    # Process links
    for actual_path, link in config.get("links", {}).items():
        log(args, "info", f"undeploy: {link} -> {actual_path}")
        ok, error = delete_symlink(link, args)
        if not ok:
            log(args, "error", f"failed to delete link: {error}")
            success = False

    # Process dependencies
    for dep_name, dep_path in config.get("dependencies", {}).items():
        dep_dir = current_dir / dep_path

        try:
            os.chdir(dep_dir)
            dep_config = dep_dir / "xdotter.toml"
            if dep_config.exists():
                if not undeploy_on(str(dep_config), args):
                    success = False
        except FileNotFoundError:
            log(args, "error", f"Dependency directory not found: {dep_dir}")
            success = False
        except OSError as e:
            log(args, "error", f"failed to enter {dep_dir}: {e}")
            success = False
        finally:
            os.chdir(current_dir)

    return success


def cmd_validate(args) -> bool:
    """
    Validate configuration file syntax.
    
    Args:
        args: Command line arguments
        
    Returns:
        True if all configs are valid, False otherwise
    """
    # Files to check
    if hasattr(args, 'files') and args.files:
        files_to_check = [Path(f) for f in args.files]
    else:
        # Default: check xdotter.toml and xdotter.json
        files_to_check = [Path("xdotter.toml"), Path("xdotter.json")]
    
    all_valid = True
    results = []
    
    for filepath in files_to_check:
        if not filepath.exists():
            # Skip default files that don't exist
            if filepath.name in ['xdotter.toml', 'xdotter.json']:
                continue
            
            log(args, "error", f"File not found: {filepath}")
            all_valid = False
            continue
        
        # Validate
        is_valid, msg = validate_config(filepath)
        
        if is_valid:
            fmt = detect_config_format(filepath).upper()
            log(args, "info", f"{COLOR_GREEN}{COLOR_RESET} {filepath} ({fmt}) - Valid syntax")
            results.append((filepath, True))
        else:
            log(args, "error", msg)
            all_valid = False
            results.append((filepath, False))
    
    # Summary
    if not args.quiet and results:
        total = len(results)
        valid = sum(1 for _, v in results if v)
        invalid = total - valid
        
        log(args, "info", "")
        if invalid == 0:
            log(args, "info", f"{COLOR_GREEN}✓ All {total} configuration file(s) have valid syntax{COLOR_RESET}")
        else:
            log(args, "warning", f"{COLOR_RED}{invalid}/{total} configuration file(s) have syntax errors{COLOR_RESET}")
    
    return all_valid


def cmd_check_perms(args) -> bool:
    """
    Check and optionally fix permissions for deployed symlinks.

    This command checks the permissions of files that have been deployed
    via symlinks to sensitive locations (SSH keys, shell configs, etc.).
    """
    config_file = "xdotter.toml"
    log(args, "debug", f"Checking permissions from {config_file}")

    try:
        with open(config_file, "r", encoding="utf-8") as f:
            content = f.read()
    except FileNotFoundError:
        log(args, "error", f"Config file not found: '{config_file}'")
        return False
    except PermissionError as e:
        log(args, "error", f"Permission denied reading '{config_file}': {e}")
        return False
    except OSError as e:
        log(args, "error", f"Failed to read config '{config_file}': {e}")
        return False

    try:
        config = ConfigParser.parse(content)
    except Exception as e:
        log(args, "error", f"Failed to parse config: {e}")
        return False
    
    home_dir = get_home_dir()
    success = True
    checked_count = 0
    fixed_count = 0
    
    # Check permissions for all links
    for actual_path, link in config.get("links", {}).items():
        link_path = Path(link.replace("~", str(home_dir))).expanduser()
        
        # Only check if symlink exists
        if not link_path.is_symlink():
            log(args, "debug", f"Skipping {link}: not a symlink")
            continue
        
        # Get the target file (resolve symlink)
        try:
            target_path = link_path.resolve()
        except OSError as e:
            log(args, "error", f"Cannot resolve {link}: {e}")
            success = False
            continue
        
        # Check if this is a sensitive path
        perm_info = get_required_permission(link_path)
        
        if perm_info:
            required_mode, description = perm_info
            checked_count += 1
            
            # Check permission
            is_correct, msg = check_permission(target_path, required_mode, description, args)
            
            if is_correct:
                log(args, "info", msg)
            else:
                log(args, "warning", msg)
                
                # Fix if requested
                if getattr(args, 'fix_permissions', False):
                    if args.dry_run:
                        log(args, "info", f"Would fix permission for {target_path}")
                    else:
                        ok, fix_msg = fix_permission(target_path, required_mode, args)
                        log(args, "info", fix_msg)
                        if ok:
                            fixed_count += 1
                        else:
                            success = False
                else:
                    success = False  # Report failure if not fixing
    
    # Summary
    if not args.quiet:
        log(args, "info", f"Checked {checked_count} sensitive file(s)")
        if getattr(args, 'fix_permissions', False):
            log(args, "info", f"Fixed {fixed_count} file(s)")
    
    return success


def cmd_new():
    """Create a new xdotter.toml template"""
    template = """# xdotter configuration file
# See: https://github.com/cncsmonster/xdotter

[links]
# Format: "source_path" = "target_link"
# Example:
".config/nvim/init.lua" = "~/.config/nvim/init.lua"
".zshrc" = "~/.zshrc"

[dependencies]
# Format: "name" = "relative_path"
# Example:
# "go" = "testdata/go"
# "nvim" = "config/nvim"
"""

    config_file = "xdotter.toml"
    with open(config_file, "w") as f:
        f.write(template)

    print(f"Created {config_file}")


def cmd_completion(args) -> int:
    """
    Generate shell completion scripts.

    Usage:
        xd completion bash
        xd completion zsh
        xd completion fish

    Uses simplified completion scripts designed for eval usage.
    """
    if not hasattr(args, 'shell') or not args.shell:
        log(args, "error", "Shell name required")
        log(args, "info", "Usage: xd completion <bash|zsh|fish>")
        return 1

    shell = args.shell.lower()

    if shell == 'bash':
        print(BASH_EVAL_COMPLETION)
        return 0
    elif shell == 'zsh':
        print(ZSH_EVAL_COMPLETION)
        return 0
    elif shell == 'fish':
        print(FISH_COMPLETION)
        return 0
    else:
        log(args, "error", f"Unsupported shell: '{shell}'")
        log(args, "info", "Supported shells: bash, zsh, fish")
        return 1


# Simplified completion scripts designed for eval usage
# These scripts work better with eval "$(xd completion <shell>)" pattern
# Note: We use $(which xd) to ensure we call the correct executable

BASH_EVAL_COMPLETION = r'''
_xd_completion() {
    local IFS=$'\013'
    local COMPLETIONS
    local XD_PATH
    XD_PATH=$(which xd 2>/dev/null) || XD_PATH="xd"
    COMPLETIONS=($(IFS="$IFS" \
        COMP_LINE="$COMP_LINE" \
        COMP_POINT="$COMP_POINT" \
        COMP_TYPE="$COMP_TYPE" \
        COMP_WORDBREAKS="$COMP_WORDBREAKS" \
        _ARGCOMPLETE=1 \
        _ARGCOMPLETE_SHELL="bash" \
        _ARGCOMPLETE_SUPPRESS_SPACE=1 \
        _ARGCOMPLETE_IFS=$'\013' \
        "$XD_PATH" 8>&1 9>&2 1>/dev/null 2>&1))
    if [[ ${#COMPLETIONS[@]} -gt 0 ]]; then
        COMPREPLY=("${COMPLETIONS[@]}")
        if [[ "${COMPREPLY[-1]}" =~ [=/:]$ ]]; then
            compopt -o nospace 2>/dev/null
        fi
    fi
}
complete -F _xd_completion xd
'''

ZSH_EVAL_COMPLETION = r'''
# Load completion system if not already loaded
autoload -Uz compinit && compinit 2>/dev/null || true

_xd_completion() {
    local -a completions
    local XD_PATH
    XD_PATH=$(which xd 2>/dev/null) || XD_PATH="xd"
    
    # Capture completions from xd in a subshell with proper environment
    completions=("${(@f)$(
        export _ARGCOMPLETE=1
        export _ARGCOMPLETE_SHELL="zsh"
        export _ARGCOMPLETE_SUPPRESS_SPACE=1
        export _ARGCOMPLETE_IFS=$'\n'
        export COMP_LINE="$BUFFER"
        export COMP_POINT="$CURSOR"
        "$XD_PATH" 8>&1 9>&2 1>/dev/null 2>&1
    )}")
    
    if [[ ${#completions[@]} -gt 0 && -n "${completions[1]}" ]]; then
        local -a replies
        local comp
        # Parse "completion:description" format
        for comp in "${completions[@]}"; do
            if [[ "$comp" == *:* ]]; then
                # Has description - use compadd with -l and -d
                replies+=("${comp%%:*}")
            else
                replies+=("$comp")
            fi
        done
        compadd -a replies
    fi
}
compdef _xd_completion xd
'''

FISH_COMPLETION = r'''function __fish_xd_complete
    set -l XD_PATH (which xd 2>/dev/null)
    if test -z "$XD_PATH"
        set XD_PATH xd
    end
    set -lx _ARGCOMPLETE 1
    set -lx _ARGCOMPLETE_SHELL fish
    set -lx _ARGCOMPLETE_IFS \n
    set -lx COMP_LINE (commandline -p)
    set -lx COMP_POINT (string length (commandline -cp))
    "$XD_PATH" 8>&1 9>&2 1>/dev/null 2>&1
end
complete -c xd -a '(__fish_xd_complete)' -f
'''


def print_help():
    """Print help message"""
    help_text = f"""xdotter - A simple dotfile manager (v{VERSION})

USAGE:
    xd [COMMAND] [OPTIONS]

COMMANDS:
    deploy              Deploy dotfiles (default command)
    undeploy            Remove deployed dotfiles
    check-permissions   Check/fix permissions for deployed files
    validate            Validate configuration file syntax
    completion          Generate shell completion scripts
    new                 Create a new xdotter.toml template
    help                Print this help message
    version             Print version

OPTIONS:
    -v, --verbose           Show more information
    -q, --quiet             Do not print any output
    -n, --dry-run           Show what would be done without making changes
    -i, --interactive       Ask for confirmation when unsure
    -f, --force             Force overwrite existing files
    --check-permissions     Check permissions for sensitive files (SSH, GPG, etc.)
    --fix-permissions       Fix permissions for sensitive files
    --no-validate           Skip config syntax validation during deploy

EXAMPLES:
    xd                            Deploy using xdotter.toml
    xd deploy -v                  Deploy with verbose output
    xd deploy --check-permissions Check sensitive file permissions
    xd deploy --fix-permissions   Fix sensitive file permissions
    xd validate                   Validate configuration file syntax
    xd completion bash            Generate Bash completion script
    xd check-permissions --fix-permissions  Fix permissions for deployed files
    xd undeploy -n                Dry-run undeploy
    xd new                        Create new configuration

INSTALLATION:
    # Download
    curl -L https://github.com/cncsmonster/xdotter/releases/latest/download/xd.pyz -o ~/.local/bin/xd

    # Make executable
    chmod +x ~/.local/bin/xd

    # Run
    xd --help

LICENSE:
    MIT License - See LICENSE file for details
"""
    print(help_text)


def print_version():
    """Print version and build information"""
    print(f"xdotter {VERSION}")
    
    # Print build info if available
    if BUILD_INFO:
        if BUILD_INFO.get('time'):
            print(f"Built: {BUILD_INFO['time']}")
        if BUILD_INFO.get('commit'):
            print(f"Commit: {BUILD_INFO['commit']}")


def main():
    """Main entry point"""
    parser = argparse.ArgumentParser(
        prog="xd",
        description="xdotter - A simple dotfile manager",
        add_help=False,
    )

    parser.add_argument(
        "command",
        nargs="?",
        choices=["deploy", "undeploy", "check-permissions", "validate", "completion", "new", "help", "version"],
        help="Command to execute",
    )
    parser.add_argument(
        "-v", "--verbose",
        action="store_true",
        help="Show more information"
    )
    parser.add_argument(
        "-q", "--quiet",
        action="store_true",
        help="Do not print any output"
    )
    parser.add_argument(
        "-n", "--dry-run",
        action="store_true",
        help="Show what would be done without making changes"
    )
    parser.add_argument(
        "-i", "--interactive",
        action="store_true",
        help="Ask for confirmation when unsure"
    )
    parser.add_argument(
        "-f", "--force",
        action="store_true",
        help="Force overwrite existing files"
    )
    parser.add_argument(
        "--no-validate",
        action="store_true",
        dest="no_validate",
        help="Skip config syntax validation during deploy"
    )
    parser.add_argument(
        "--shell",
        help="Shell name for completion command (bash|zsh|fish)"
    )
    parser.add_argument(
        "files",
        nargs="*",
        help="Configuration files to validate (for validate command)"
    )
    parser.add_argument(
        "-h", "--help",
        action="store_true",
        help="Print this help message"
    )
    parser.add_argument(
        "--version",
        action="store_true",
        help="Print version"
    )
    parser.add_argument(
        "--check-permissions",
        action="store_true",
        dest="check_permissions",
        help="Check permissions for sensitive files (SSH keys, GPG, etc.)"
    )
    parser.add_argument(
        "--fix-permissions",
        action="store_true",
        dest="fix_permissions",
        help="Fix permissions for sensitive files (implies --check-permissions)"
    )

    # Enable argcomplete autocomplete (if available)
    # This is automatically activated when COMP_LINE env var is set by bash
    try:
        from _vendor.argcomplete import autocomplete
        autocomplete(parser)
    except (ImportError, TypeError):
        # argcomplete not vendored or not running in completion context
        pass

    args = parser.parse_args()
    
    # --fix-permissions implies --check-permissions
    if args.fix_permissions:
        args.check_permissions = True

    # Handle help and version first
    if args.help or args.command == "help":
        print_help()
        return 0

    if args.version or args.command == "version":
        print_version()
        return 0

    # Handle new command
    if args.command == "new":
        cmd_new()
        return 0

    # Handle completion command
    if args.command == "completion":
        # Support both --shell flag and positional argument for backward compatibility
        if hasattr(args, 'shell') and args.shell:
            args.shell = args.shell
        elif hasattr(args, 'files') and args.files:
            args.shell = args.files[0]
        return cmd_completion(args)

    # Handle validate command
    if args.command == "validate":
        if args.dry_run:
            log(args, "info", "Validating configuration (dry-run)...")
        else:
            log(args, "info", "Validating configuration...")
        success = cmd_validate(args)
        return 0 if success else 1

    # Handle check-permissions command
    if args.command == "check-permissions":
        if args.dry_run:
            log(args, "info", "Checking permissions (dry-run)...")
        else:
            log(args, "info", "Checking permissions...")
        success = cmd_check_perms(args)
        return 0 if success else 1

    # Default to deploy if no command specified
    command = args.command or "deploy"

    if command == "deploy":
        if args.dry_run:
            log(args, "info", "Deploying (dry-run)...")
        else:
            log(args, "info", "Deploying...")
        success = deploy_on("xdotter.toml", args)
        return 0 if success else 1

    elif command == "undeploy":
        if args.dry_run:
            log(args, "info", "Undeploying (dry-run)...")
        else:
            log(args, "info", "Undeploying...")
        success = undeploy_on("xdotter.toml", args)
        return 0 if success else 1

    return 0


if __name__ == "__main__":
    sys.exit(main())